[英]When authoring a jquery plugin, how do I call one of my main plugin methods from another method?
我正在遵循 jquery 網站上的插件創作指南,但我無法弄清楚如何從同一個插件中的另一個方法調用主插件方法。
我有一個這樣的插件:
(function($){
var methods = {
init: function(options) {
var settings = {};
//this == context element of plugin, already jquery
return this.each(function() {
var $this = $(this);
if( options ) {
settings = $.extend({}, settings, options);
}
var data = $this.data('PluginData');
if(!data) {
//set up
}
});
},
some_fn: function() {
//do some stuff
},
another_fn: function() {
//do other stuff, then somehow call some_fn(), maybe via methods.some_fn() ?
}
};
jQuery.fn.SomePlugin = function(method) {
if(methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call( arguments, 1));
} else if (typeof(method) == 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
console.log('there was an error');
}
};
})(jQuery);
這幾乎是來自 jquery 的骨架代碼。 但是,我遇到的麻煩是找出創建僅適用於我的插件方法的“實用程序”function 的最佳方法,或者如何從另一個插件方法調用一個插件方法。
例如,在我的插件中,我有 3 個方法, init
、 some_fn
和another_fn
。 當我在 another_fn 中調用$('#el').SomePlugin('another_fn')
another_fn
,我想調用some_fn
。 我怎樣才能做到這一點? 調用methods.some_fn()
可能會起作用,但是,這取決於方法在方法 object 中定義的順序,對嗎? 所以我可以從another_fn
調用some_fn
,但反之不行?
此外,創建我的插件中的所有方法都可以使用的實用程序 function 的正確方法是什么,這樣我就不會弄亂全局命名空間? 我是否只是在我的插件開始時,在調用 var 方法之前定義實用程序函數?
編輯:感謝 Matt Ball,我已經確認 methods.some_fn() 確實可以調用其他主要方法。 現在我只想知道創建(私有)實用程序 function 的最佳實踐是什么
要獲得最佳實踐,您應該查看: http://jqueryboilerplate.com他們為您的問題提供了示例。 :)
對於您的示例,您可以利用init
function 的 scope:
(function($){
var methods = {
init: function(options) {
var settings = {};
var privateMethod = function(){ ... }
//this == context element of plugin, already jquery
return this.each(function() {
var $this = $(this);
if( options ) {
settings = $.extend({}, settings, options);
}
var data = $this.data('PluginData');
if(!data) {
//set up
}
});
},
some_fn: function() {
//call private function
privateMethod()
// do some stuff
}
};
jQuery.fn.SomePlugin = function(method) {
if(methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call( arguments, 1));
} else if (typeof(method) == 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
console.log('there was an error');
}
};
})(jQuery);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.