我一直在使用jQuery Boilerplate来开发插件,而我无法弄清楚的一件事是如何从插件外部调用方法.
作为参考,这里是我正在谈论的样板代码:http: //jqueryboilerplate.com/
在我的小提琴,
这是代码:
;(function ( $, window, document, undefined ) {
var pluginName = 'test';
var defaults;
function Plugin(element, options) {
this.element = element;
this.options = $.extend( {}, defaults, options) ;
this._name = pluginName;
this.init();
}
Plugin.prototype = {
init: function() {
this.hello();
},
hello : function() {
document.write('hello');
},
goodbye : function() {
document.write('goodbye');
}
}
$.fn[pluginName] = function ( options ) {
return this.each(function () {
if (!$.data(this, 'plugin_' + pluginName)) { …Run Code Online (Sandbox Code Playgroud) 我现在已经编写了我的第四个插件,我开始注意到我的开发模式中的趋势,并且不确定是否有更好的方法来处理它.
我正在使用插件方法(Addy Osmani概述的轻量级启动模式,请参见此处:http://addyosmani.com/resources/essentialjsdesignpatterns/book/#jquerypluginpatterns)
在我的Plugin.prototype中,我有一堆方法,包括init()函数,我用它来调用插件中的所有方法.原谅这种混乱,但这就是它的样子:
Plugin.prototype = {
init: function() {
this.doMethodOne();
this.doMethodTwo(this.element, this.options)
this.doMethodThree();
},
doMethodOne: function() { .. }
doMethodTwo: function(el, options) { .. }
doMethodThree: function() { .. }
}
$.fn[pluginName] = function ( options ) {
return this.each(function () {
if (!$.data(this, 'plugin_' + pluginName)) {
$.data(this, 'plugin_' + pluginName,
new Plugin( this, options ));
}
});
}
Run Code Online (Sandbox Code Playgroud)
我遗漏了一些信封代码,但我希望你能得到这个想法.
我发现我的代码有点缺乏,因为我只是线性地调用我的代码并将其存储在插件名称空间中.
我已多次阅读插件开发模式和创作文本,仍然以这种方式编写.我怎样才能改善这个?
谢谢 !