Marc
Marc

Reputation: 698

how to avoid long namespaces in Javascript

We are starting a new project and we have decided to use javascript ""namespaces"" to organize our client side code. The thing is that we have noticed that we can end very easily with super-long namespaces that are dificult to remember like

myProject.components.myComponent.doSomethig();

Is there any better way to do this or create some kind of "alias" somehow?

Thanks.

Upvotes: 1

Views: 630

Answers (3)

Guumaster
Guumaster

Reputation: 389

In JavaScript, you can make shortcut references to long namespaces stuff

 var myComp = myProject.components.myComponent;
 myComp.func1();

This is a reference only. You can do this with other long names and write less like this

 var getEl = document.getElementById, 
     myEl = getEl('divId');

Also you can organize your code with RequireJS to organize your code

// file: myProject/components/myComponent.js

 define(function(){
       var myComponent ={};
       myComponent.func1 = function(){
           ...
       }
       return myComponent;
 });

// file: myProject/main.js

 require(['myProject/components/myComponent',  'myProject/components/myComponent2'], 
 function(comp1, comp2){
         var main = {};
         main.init = function() {
             ...
             comp1.func1();
         }
 });

// file: myProject/index.html

 <script src="libs/require.js" data-main="myProject/main"></script>

Upvotes: 4

T.J. Crowder
T.J. Crowder

Reputation: 1074238

If you use scoping functions around your module code (and if you don't, you should), then you can create local aliases quite easily as variables shared by all of the functions within a given module.

E.g., code defining the myComponent component:

(function() {
    var comp = {};

    // Export our component
    myProject.components.myComponent = comp;

    // add things to `comp`; since `comp` and `myProject.components.myComponent`
    // refer to the same object, adding to `comp` is adding to the one object
    // they both refer to and so you can access those things via either reference
})();

Similarly if you're writing app code that uses multiple components:

(function() {
    var thisComp = myProject.components.thisComponent,
        thatComp = myProject.components.thatComponent;

    // Use `thisComp` and `thatComp`
})();

Upvotes: 1

ThiefMaster
ThiefMaster

Reputation: 318498

You can always store a subnamespace in a local variable:

var myComponent = myProject.components.myComponent;

Upvotes: 0

Related Questions