这就是我想出的:在包含使用它的插件之前,将以下函数放入您包含的某个库中:
function PluginMaker() {
var plugin = url2fn($('script:last').attr('src'));
$.fn[plugin] = function (opts) {
opts = $.extend(true, {}, $[plugin], opts);
for (fn in opts.fx) this[fn] = fxmk(fn); // auto-vivification of methods
this.each(function () { if (!this['$' + plugin]) this['$' + plugin] = opts; });
opts.init(opts); // plugin initialisation
this.init(opts); // per-object initialisation
return this;
};
function fxmk(nm) {
return function () {
var args = arguments;
this.each(function () {
this['$' + plugin].fx[nm].apply(this, args);
});
return this;
};
}
return plugin;
}
然后像这样定义你的插件:
// -- myplugin.js ---------------------------------------------------------------
(function ($) {
$[PluginMaker()] = {
// whatever state data you want to keep for your plugin
fx: {
MyMethod1: function () { /* within these methods */ },
MyMethod2: function (msg) { /* this refers to the HTML element */ },
// whatever other methods you want to define
init: function (opts) {
// used for per-element initialisation
}
},
init: function(opts) {
// used for plugin initialisation (one time)
}
};
});
然后,包含插件后,您可以执行以下操作:
$('.class').MyPlugin({ /* whatever options */ });
$('.class').MyMethod1();
甚至:
$('#someId').MyMethod2();