【发布时间】:2013-11-29 00:59:22
【问题描述】:
目前我正在使用这个“模板”构建我的 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 中做到这一点......
【问题讨论】:
标签: javascript jquery object jquery-plugins