目前我正在建设使用这个“模板”我的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