Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - make global variable available to multiple plugins

I have a set of jQuery plugins I'm creating for a website.

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.

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?

like image 948
frankadelic Avatar asked Dec 07 '22 05:12

frankadelic


1 Answers

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

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);
    });
}
like image 110
Doug Neiner Avatar answered Mar 19 '23 11:03

Doug Neiner