RequireJS load same module twice to get two separate namespaces
Problem
This example library, which uses RequireJS under a browser and uses amdefine instead under Node.js:
lib.js
if (typeof define !== 'function') { var define = require('amdefine')(module); }
define([],function () {
var opt = 0
return {
set: function(x) { opt = x },
show: function() { console.log(opt) }
}
})
Now here this library is used by the node sample program
srv.js
var lib=require('./lib')
lib.set(111)
var lib2=require('./lib')
lib2.set(222)
lib.show()
lib2.show()
This is example program identical to above, but for a browser instead
index.html
cli.js
requirejs(['lib','lib'], function(lib, lib2) {
lib.set(111)
lib2.set(222)
lib.show()
lib2.show()
});
both program will output:
console log
222
222
but desired output is
console log
111
222
This is because the actual module is loaded only once, is there a way to tell RequireJS to load module twice, or in other words have two separate namespaces?
Problem courtesy of: exebook
Solution
why not create namespace inside lib (http://jsfiddle.net/cFEeR/1/):
if (typeof define !== 'function') { var define = require('amdefine')(module); }
define('lib',function () {
var namespaces = {}
var Namespace = function() {
this.opt = 0
}
Namespace.prototype.set = function(x) { this.opt = x },
Namespace.prototype.show = function() { console.log(this.opt) }
return function(name) {
if (!namespaces[name]) namespaces[name] = new Namespace()
return namespaces[name]
}
})
requirejs(['lib'], function(Lib) {
var lib = Lib('test')
var lib2 = Lib('test1')
lib.set(111)
lib2.set(222)
lib.show()
lib2.show()
});
Solution courtesy of: krasu
Discussion
View additional discussion.