Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
48
rated 0 times [  54] [ 6]  / answers: 1 / hits: 15602  / 12 Years ago, fri, march 16, 2012, 12:00:00

I plan to use the following pattern to make use of the requireJS based module to act as a singleton. Please notice that classA returns an instance of type 'classA', whereas the rest of the classes classB, classC, and main return the type of the class from the module. All of these are classes based on the MooTools Class.



The idea is to use the classA as a globally available singleton, the methods are just fillers. Any thoughts if this is an acceptable pattern to use?



Will this come back to bite me at a later stage? I haven't tried to run r.js on the project yet, so I am a bit worried, and look for some advise.



    // classA.js
define([], function() {
var classA = new Class({

initialize: function (regionId) {
// perform some Initialization.
this.data = null;
},

doSomething: function(param) {
// some thing.
this.data = param;
}
};

return new classA();
});

// classB.js
define([classA], function(classA) {
var classB = new Class({

initialize: function (regionId) {
// perform some Initialization.
},

doSomethingElse: function() {
// some thing.
classA.doSomething(Go back to Work Now!);
}
};

return classB;
});


// classC.js
define([classA], function(classA) {
var classB = new Class({

initialize: function (regionId) {
// perform some Initialization.
},

doSomethingElse: function() {
// some thing.
classA.doSomething(Time to Play!);
}
};

return classC;
});


// main.js
define([classA, classB, classC], function(classA, classB, classC) {
var main = new Class({

initialize: function (regionId) {
// perform some Initialization.
this.b = new classB();
this.c = new classC();
},

doEverything: function() {
// some thing.
this.b.doSomethingElse();
classA.doSomething(Nap Time!);
}
};

return main;
});


Thanks much in advance...


More From » requirejs

 Answers
54

No, I cannot think of a reason against using singletons with require.js.



Your module definition should export the singleton. The way you do it is fine, since it's a singleton you might be also able to avoid the new. I use something like



define(function (require) {
var singleton = function () {
return {
...
};
};
return singleton();
});


The first require to the module will load and export it. Some other module requiring your singleton will just reuse the already exported one.


[#86805] Thursday, March 15, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
devonw

Total Points: 311
Total Questions: 116
Total Answers: 111

Location: Senegal
Member since Fri, Aug 21, 2020
4 Years ago
;