JavaScript has no namespaces. However, when most of us refer to namespaces in the context of JavaScript, we really mean storing our functions and data in objects in a modular way without cluttering the global context.
There are several libraries that handle dependency management and script loading, but I'm not going to distribute this right now:
To create a namespace, you must first create an object in a global context.
Creating a namespace:
At the most basic level, it is just as simple:
window["MyOrg"] = {};
Typically, your base object will not have any data or functions, but rather will consist of submodules. The simplest form for creating submodules is almost the same:
MyOrg.submodule = {}
You can expand this template to any level you want. e.g. MyOrg.submodule.tools.usefulFunction
Note If you define your modules and auxiliary modules in different files that can be loaded in random order, you must first check if your namespace (and any parent modules) exists 1) you do not get an error when defining your module and 2), so as not to overwrite any modules, but increase them.
For example, if you define the module MyOrg.submodule , you need to include:
var MyOrg = MyOrg || {}; MyOrg.submodule = MyOrg.submodule || {};
Now that you have your submodule installed, you can easily assign it to members using the expected notation:
MyOrg.submodule.add = function (x, y) { return x + y; } MyOrg.submodule.CONSTANT = 42;
If you can guarantee that you are defining a submodule for the first time (without the risk of overwriting anything), you can also use:
MyOrg.submodule = { add: function (x, y) { return x + y; }, CONSTANT: 42 };
Advanced Methods
Well, you have to understand the essence of this. However, there are several more advanced templates that you can follow, in particular, "Module outline:"
MyOrg = MyOrg || {}; MyOrg.submodule = (function () { var privateVariable = 42; return { getVar: function () { return privateVariable; }, setVar: function (value) { privateVariable = value; } }; })();
You use your modules using the same exact notation, but with the added benefit of having private variables and functions:
MyOrg.submodule.setVar(2); MyOrg.submodule.getVar();
As for your second question, you can do this in several ways.
You can first add server-side javascript to generate with the relevant data that has already been baked.
var MyOrg = MyOrg || {}; MyOrg.userInfo = { userName: "<%= @user.user_name %>", location: "<%= @user.location %>"
You can also get it from the server from the client side using AJAX and JSON
$.ajax({ url: "user/getInfo", success: function (data) {
If you use this method, you may have to use callbacks in your user module to get the relevant information, or you can implement caching methods (with the added benefit of not creating so many server requests).