您需要在您的默认值来定义你的默认名称和Foo事件DECL aration:
$.fn.myPlugin.defaults = {
name: 'test',
onFoo: function() {
alert(this.name);
},
onFoo2: function() {
// your default behaviour for foo2
}
};
然后,当有人拨打你的插件,就可以覆盖默认值,在这种情况下name
:
$("#myControl").myPlugin({
name: 'test2'
});
注意,他们并不需要重写onFoo,因为它会显示带有test2的警报。无论如何,如果他们需要重写它做不同的事情,那么他们应该:
$("#myControl").myPlugin({
name: 'test2',
onFoo: function() {
alert('onFoo overrired');
},
onFoo2: function() {
alert('onFoo2 overrired');
}
});
在你的插件,你调用foo的方法为
(function($) {
$.fn.myPlugin = function(options) {
var opt = $.extend({}, $.fn.myPlugin.defaults, options);
// if onFoo is defined then call it
if (opt.onFoo) {
opt.onFoo();
}
// if onFoo2 is defined then call it
if (opt.onFoo2) {
opt.onFoo2();
}
}
$.fn.myPlugin.defaults = {
name: 'test',
onFoo: function() {
alert(this.name);
},
onFoo2: function() {
// your default behaviour for foo2
}
};
});
你应该使用这种技术的公共方法/属性,你想暴露给你的插件的用户。 我没有测试,但应该工作
编辑 您需要检查,如果该事件被设置调用前:
// if onFoo is defined (not null) then call it
if (opt.onFoo) {
opt.onFoo();
}
你已经在为onFoo和onFoo2事件,但你的插件的用户可以选择禁用它:
$("#myControl").myPlugin({
onFoo: null
});
在这种情况下,虽然你已经定义了一个onFoo
事件,你的插件的用户决定ignor通过将其设置为null
。所以,即使你已经定义了一个事件,你永远不知道别人会用它来做什么,因此最好保持安全并检查是否为空。
再次,你需要小心你暴露给最终用户的东西,因为设置/取消设置的事件不应该打破你的插件
该代码在语法上不合法的基本功能。 – Pointy 2011-05-18 13:08:32
你看过http://docs.jquery.com/Plugins/Authoring吗?它可能有帮助... – 2011-05-18 13:21:37