我開始瞭解更多關於jQuery插件模式的知識,但我遇到了一些問題。見下面的代碼。我想用onclick函數訪問我的插件選項/默認值,但我不知道如何。如何從事件函數中訪問其他方法?
function SomePlugin(element,options)
{
this.$el = $(element);
this.options = $.extend({},
{
button: '#button',
someVariable:'fuu',
anotherVariable:'bar'
},options);
this.init();
}
SomePlugin.prototype =
{
init:function()
{
var button = this.$el.find(this.options.button)
button.on('click', this.onClick);
},
onClick: function(event){
// Need to access the options (someVariable, anotherVariable) here... how?
}
};
$.fn.somePlugin = function(options)
{
return this.each(function()
{
if(!$.data(this,'somePlugin'))
{
$.data(this,'somePlugin',new SomePlugin(this,options));
}
});
};
我試過了下面的代碼,但是由於某種原因,這種感覺並不正確。有沒有更好的辦法?此外,我還有其他關於我的插件結構的建議或提示,請讓我知道。 BTW我已經離開了jQuery的包裝的可讀性
function SomePlugin(element,options)
{
this.el = element;
this.$el = $(element);
this.options = $.extend({},
{
button: '#button',
someVariable:'fuu',
anotherVariable:'bar'
},options);
this.init();
}
SomePlugin.prototype =
{
init:function()
{
var button = this.$el.find(this.options.button)
button.on('click', {instance:this}, this.onClick);
},
onClick: function(event){
// Options can be accessed using event.data.instance.options ... is there an easier way?
}
};
$.fn.somePlugin = function(options)
{
return this.each(function()
{
if(!$.data(this,'somePlugin'))
{
$.data(this,'somePlugin',new SomePlugin(this,options));
}
});
};
感謝隊友,我會研究它。你有任何機會回答我的問題? – Michiel 2013-03-21 10:02:29