目前我正在建設使用這個「模板」我的jQuery插件:Abstractize jQuery插件創建
;(function($, window, document){
var defaultOptions = {
option1: value1,
option2: value2,
};
function plugin(el, options){
this.options = $.extend({}, defaultOptions, options);
this.el = el;
this.__construct();
};
plugin.prototype = {
__construct: function(){
// do the plugin stuff, set up events etc.
},
__destruct: function(){
$(this.el).removeData('myPlugin');
},
// other plugin functions here...
};
$.fn.myPlugin = function(options){
var additionalArguments = Array.prototype.slice.call(arguments, 1);
return this.each(function(){
var inst = $.data(this, 'myPlugin');
if(!(inst instanceof plugin)){
var inst = new plugin(this, options);
$.data(this, 'myPlugin', inst);
return inst;
}
if(typeof options == 'string'){
inst[options].apply(inst, additionalArguments);
}
});
};
$(document).ready(function(){
$('.my-plugin').myPlugin();
});
})(jQuery, window, document);
我得到了大部分意見,從https://github.com/jquery-boilerplate/jquery-boilerplate/blob/master/src/jquery.boilerplate.js
所以這個例子並沒有什麼,它只是插件的「骨幹」,正如你可以看到它是相當多的代碼....
我可以建立某種插件的創造者功能,可以讓我把上面的代碼改寫成更小的東西:
createPlugin('myPlugin', {
defaultOptions: {},
__construct: function() {
...
},
__destruct: function() {
...
},
somePublicFunction: function(){
...
}
});
但仍然可以使用它像
$('.element').myPlugin();
?
在PHP中我會使用抽象類爲這樣的事情,但我不知道如何做到這一點在JavaScript ...
實際上想要'this' not'$(this)'' – charlietfl