jQuery - 使全局变量可用于多个插件 [英] jQuery - make global variable available to multiple plugins
问题描述
我有一个为网站创建的jQuery插件。
I have a set of jQuery plugins I'm creating for a website.
所有这些插件都有它们的通用功能$ .getJSON 。
All of these plugin have the common functionality that they make $.getJSON() calls.
这些调用中传递的网址根据开发人员,质量保证和生产环境而异。
The URL passed in these calls varies based on Dev, QA and production environments.
将网址存储在中心位置,以便轻松更改。
I would like to store the URL in a central place so it can be easily changed.
网址应存储在哪里?我不想将URL存储在每个单独的插件。
它可以定义为一个全局变量,还是最好将其作为传递给插件的参数?
Where should the URL be stored? I don't want to store the URL in each individual plugin. Can it be defined as a global variable or is it better to make it an argument passed to the plugin?
推荐答案
我建议你使用附加到jQuery对象的对象字面量。只要确保在所有插件之前包含它:
I would recommend you use an object literal attached to the jQuery object. Just be sure to include it before all your plugins:
jQuery.YourCompany = {
url: "http://thedomain.com"
};
然后在任何需要的地方,只需使用
Then anywhere you need it, just use
jQuery.YourCompany.url
// or
$.YourCompany.url
如果使用对象/类与 $。fn
函数组合,还可以将此全局变量用作命名空间:
If you use objects/classes in combination with the $.fn
functions, you can also use this global variable as a namespace:
jQuery.YourCompany.PluginOne = function(el){
....
}
// But not on the fn object:
jQuery.fn.pluginOne = function(){
return this.each( function() {
var po = new jQuery.YourCompany.PluginOne(this);
});
}
这篇关于jQuery - 使全局变量可用于多个插件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!