How to create a global javascript object that can be accessed outside of my JS file?

I have the following object in a JS file:

var IOBreadcrumb = function IOBreadcrumb() { this.breadcrumbs = []; this.add = function(title, url) { var crumb = { title: title, url:url }; this.breadcrumbs.push(crumb); }; }; 

In another JS file, I want to use this object:

 //this occurs in some on click event var breadcrumb = new IOBreadcrumb(); breadcrumb.add('some title',url); console.log(breadcrumb.breadcrumbs); 

I would like there to be only 1 instance of IOBreadcrumb, so when I click the button, it will always add a bundle to the array.

How can i do this?

+4
source share
3 answers
 var IOBreadcrumb = { breadcrumbs: [], add: function(title, url) { var crumb = { title: title, url:url }; IOBreadcrumb.breadcrumbs.push(crumb); } }; 

Then:

 IOBreadcrumb.add('some title',url); console.log(IOBreadcrumb.breadcrumbs); 
+9
source

Do something like the next first javascript to be executed on your page.

 (function(){ var setup = function IOBreadcrumb() { this.breadcrumbs = []; this.add = function(title, url) { console.log('adding'); var crumb = { title: title, url:url }; this.breadcrumbs.push(crumb); } }; window.IOBreadcrumb = new setup(); })(window); 

This makes the initial setup. Now from anywhere you can do

IOBreadcrumb.add()

I tested this at http://jsfiddle.net/xmHh5/

This means that window.IOBreadcrumb assigns the result to a function that runs immediately. Since there is no handle for this function, there is no way to re-execute it. Since you put IOBreadcrumb in a window object, it is effectively global. I assume this works in a browser; it will not work on node.js or anything because it depends on window .

+4
source

Another option is to use a Module pattern , which has the advantages of keeping the breading entities truly private. Not everyone is a fan of the module template, though, since it prevents the monkey patch. This is especially problematic when you use the library, and you need to change the behavior, but you do not want to edit the source files to minimize upgrade problems. http://snook.ca/archives/javascript/no-love-for-module-pattern

 var IOBreadcrumb = (function() { var breadcrumbs = []; return { add: function(title, url) { breadcrumbs.push({ title: title, url: url }); }, each: function (callback) { for (var i=0; i < breadcrumbs.length; i++) { callback(breadcrumbs[i].title, breadcrumbs[i].url); } } } })(); IOBreadcrumb.add('title A', 'http://url.com/A'); IOBreadcrumb.add('title B', 'http://url.com/B'); IOBreadcrumb.add('title C', 'http://url.com/C'); IOBreadcrumb.each(function(title, url){ console.log('Title', title, 'Url', url); }); 
+2
source

All Articles