Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using RequireJS, how do I pass in global objects or singletons around?

Let's say I am writing code at the main page level and 2 dependencies require the same instance of an object and also state that as a dependency. What is the appropriate way to go about this?

Basically what I want to do is say, "If this dependency isn't loaded... then load it. Otherwise, use the same instance that was already loaded and just pass that one."

like image 444
egervari Avatar asked Apr 09 '11 23:04

egervari


2 Answers

You would make that a module-level variable. For example,

// In foo.js define(function () {     var theFoo = {};      return {         getTheFoo: function () { return theFoo; }     }; });  // In bar.js define(["./foo"], function (foo) {     var theFoo = foo.getTheFoo(); // save in convenience variable      return {         setBarOnFoo: function () { theFoo.bar = "hello"; }     }; }  // In baz.js define(["./foo"], function (foo) {     // Or use directly.     return {         setBazOnFoo: function () { foo.getTheFoo().baz = "goodbye"; }     }; }  // In any other file define(["./foo", "./bar", "./baz"], function (foo, bar, baz) {     bar.setBarOnFoo();     baz.setBazOnFoo();      assert(foo.getTheFoo().bar === "hello");     assert(foo.getTheFoo().baz === "goodbye"); }; 
like image 192
Domenic Avatar answered Sep 23 '22 16:09

Domenic


Just provide an API for your singleton as you would.

And make sure its lazily loaded. The easiest way is to use an abstraction library like underscore that supplies cross browser helpers. Other options are ES5 Object.defineProperty or custom getter/setters.

In this case _.once ensures that constructor's result is cached after the first call, it basically lazy loads it.

define(function() {     var constructor = _.once(function() {          ...     });      return {         doStuffWithSingleton: function() {             constructor().doStuff();         }     };  }); 

_.once from underscore.

like image 41
Raynos Avatar answered Sep 24 '22 16:09

Raynos