這是我想出了:把下面的功能在某些庫你包括包括使用它的插件前:
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();
很難理解你的意思。你可以編輯它,或繪製圖表? –