我开始了解更多关于 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));
}
});
};
我已经尝试了下面的代码,但是由于某种原因感觉不对。有没有更好的办法?另外,您对我的插件结构有任何其他建议或提示,请告诉我。顺便说一句,为了便于阅读,我省略了 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));
}
});
};