JQuery - make a global variable available to multiple plugins

I have a set of jQuery plugins that I create for a website.

All of these plugins have common functionality that they cause calls to $ .getJSON ().

The URL passed in these calls depends on Dev, QA, and production environments.

I would like to keep the URL in a central place so that it can be easily changed.

Where should the URL be stored? I do not want to save the url in every single plugin. Can it be defined as a global variable or is it better to make it an argument passed to the plugin?

+4
source share
1 answer

I would recommend using an object literal attached to a jQuery object. Just remember to include it in front of all your plugins:

jQuery.YourCompany = { url: "http://thedomain.com" }; 

Then, anywhere, just use

 jQuery.YourCompany.url // or $.YourCompany.url 

If you use objects / classes in combination with $.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); }); } 
+15
source

All Articles