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."
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"); };
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With