Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Namespace a dynamically loaded javascript file's contents

Is it possible to namespace a JavaScript file inserted dynamically?

I know that I can dynamically include a JavaScript file by creating a script tag and insert it into the DOM, but can this included file be namespaced? So, if the file has a function called bar, I would want access it through a namespace, say foo: i.e. foo.bar().

like image 700
William Niu Avatar asked Aug 14 '11 09:08

William Niu


1 Answers

Yes, CommonJS Modules/1.1 specifies only one way of doing it.

I've used it only with Node.js on server side, but I believe there are other libraries created to work with browser that are CommonJS compliant. Beware that there are multiple module specifications for server/browser (didn't dig into that yet).

Modules are written just like any other piece of javascript, the only addition is you export what you want to expose:

module.exports.bar = Bar;

function Bar() {
 // code
}

And the usage:

var foo = require('mymodule');

foo.bar();

What is actually done in the background, the whole code is wrapped into another function and exports are its properties.

Also, Michael Bolin talked about similar problem in his talk about 'with' keyword at JSConf.

like image 152
usoban Avatar answered Nov 11 '22 18:11

usoban