user656925
user656925

Reputation:

Keeping two separate javascript files / snippets in same namespace

I have two files that I load to the browser.

One is loaded directly as embedded script in the initial call.

The other is loaded dynamically by creating a script node and writing to the .innerHTML property.

I have to do things this way.

Both snippets of JavaScript are encapsulated in the module pattern.

Can I give them the same name space like this:

Pseudo-code

var ns = Module Pattern 1

var ns = Moudule Pattern 2

If not, is there another way to give them the same name space so that when they return functions I can access the functions uniformly?

ns.function1();
ns.function2();

Because this is for one application I'd prefer to have only one namespace. But as I mentioned I have to load two snippets.

Thanks

Upvotes: 0

Views: 114

Answers (1)

Scott Sauyet
Scott Sauyet

Reputation: 50787

With any reasonable mixin implementation, you might try something like:

var ns = ns || {};
mixin(ns, Module Pattern 1);

var ns = ns || {};
mixin(ns, Module Pattern 2);

Then these can be loaded in any order.


Alternately, change your module pattern a little to accept the namespace object as a parameter and supply the same one to both:

var ns = ns || {};
(function(namespace) {
    // ...
    namespace.function1 = //...
}(ns));   

// (again for module 2)

Upvotes: 1

Related Questions