Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
47
rated 0 times [  51] [ 4]  / answers: 1 / hits: 32450  / 13 Years ago, sat, april 9, 2011, 12:00:00

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.


More From » singleton

 Answers
29

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);
};

[#92829] Thursday, April 7, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
laytonlamontm

Total Points: 745
Total Questions: 130
Total Answers: 130

Location: Cambodia
Member since Thu, Oct 7, 2021
3 Years ago
;