問題描述
我正在創(chuàng)建一個范圍相當(dāng)大的 jQuery 插件.事實上,從技術(shù)上講,該插件由幾個共同工作的插件組成.
I'm creating a jQuery plugin that that is rather large in scope. In fact, the plugin technically consists of a few plugins that all work together.
(function($){
$.fn.foo = function(){
//plugin part A
}
$.fn.bar = function(){
//plugin part B
}
$.fn.baz = function(){
//plugin part C
}
}(jQuery))
是否可以為 jQuery 插件命名,以便次要插件可以是較大插件的功能
Is it possible to namespace jQuery plugins such that the minor plugins could be functions of the larger plugin
$.fn.foo.bar = function(){}
$.fn.foo.baz = funciton(){}
這樣可以避免污染 jQuery 函數(shù)命名空間.然后你可以調(diào)用插件像
This would keep from polluting the jQuery function namespace. You could then call the plugins like
$('#example').foo()
$('#other_example').foo.bar()
我自己嘗試這個時遇到的問題是聲明為 foo() 插件函數(shù)的屬性的函數(shù)沒有正確設(shè)置對this"的引用.'this' 最終指向父對象而不是 jQuery 對象.
The issue I have run into when trying this out myself is that the functions declared as properties of the foo() plugin function don't have their references to 'this' set properly. 'this' ends up referring to the parent object and not the jQuery object.
任何想法或意見將不勝感激.
Any ideas or opinions would be appreciated.
-馬特
推薦答案
只要你使用 $.fn.foo.bar()
-- this
指向$.fn.foo
,這是您在 JavaScript 中所期望的(this
是調(diào)用函數(shù)的對象.)
As soon as you use $.fn.foo.bar()
-- this
points to $.fn.foo
, which is what you would expect in JavaScript (this
being the object that the function is called on.)
我注意到 jQuery UI 的插件(如可排序)中調(diào)用的函數(shù)如下:
I have noticed in plugins from jQuery UI (like sortable) where you call functions like:
$(...).sortable("serialize");
$(...).sortable({options});
如果你正在做這樣的事情 - 你可以擴展 jQuery 本身:
If you were doing something like this - you could extend jQuery itself:
$.foo_plugin = {
bar: function() {},
baz: function() {}
}
$.fn.foo = function(opts) {
if (opts == 'bar') return $.foo_plugin.bar.call(this);
if (opts == 'baz') return $.foo_plugin.baz.call(this);
}
這篇關(guān)于jQuery 插件命名空間函數(shù)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!