Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

RequireJS load same module twice to get two separate namespaces

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.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

RequireJS load same module twice to get two separate namespaces

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×