simplified.
simplified.

Reputation: 31

Module Javascript

I was wondering, if it is possible to make this code change to a point where I can just call MyModule.RED instead of having MyModule.COLORS.RED. I tried making mod the variable to store the colors but it seems to not work. Is it that I am doing it the wrong way?

(function() {
    var mod;

// Create the global, and also give ourselves a convenient alias for it (`mod`)
window.MyModule = mod = {};

// Colors
mod.COLORS = {
    RED: "#FF0000",
    BLUE: "#0000FF",
    // ...
    GREEN: "#00FF00"
};

mod.testQuery = MyModule_testQuery;
function MyModule_testQuery() {
    // Do something
}

})();

alert(MyModule.COLORS.RED); // #FF0000
 MyModule.testQuery();       // Do something

EDIT

(function() {
    var mod;

// Create the global, and also give ourselves a convenient alias for it (`mod`)
window.MyModule = mod = {};

// Colors
mod.COLORS = {
    RED: "#FF0000",
    BLUE: "#0000FF",
    // ...
    GREEN: "#00FF00"
};

var colors = mod.COLORS;

mod.testQuery = MyModule_testQuery;
function MyModule_testQuery() {
 // Do something
}

})();

alert(colors.RED); // #FF0000
 MyModule.testQuery();       // Do something

Upvotes: 0

Views: 248

Answers (3)

kzh
kzh

Reputation: 20598

Just attach the stuff directly.

(function() {
  window.MyModule = {
      RED: "#FF0000"
    , BLUE: "#0000FF"
    , GREEN: "#00FF00"
    , testQuery = function() {
        // Do something
      }
  };
})();
alert(MyModule.RED);  // #FF0000
MyModule.testQuery(); // Do something

Upvotes: 0

InfinitiesLoop
InfinitiesLoop

Reputation: 14629

When you say "doesn't work", can you be more specific? :)

I think you're looking for this:

(function() {

// Create the global, and also give ourselves a convenient alias for it (`mod`)
window.MyModule = {
    RED: "#FF0000",
    BLUE: "#0000FF",
    GREEN: "#00FF00",
    testQuery: MyModule_testQuery
};

function MyModule_testQuery() {
   // Do something
} 

})();

alert(MyModule.RED); // #FF0000
MyModule.testQuery();       // Do something

Upvotes: 0

BiAiB
BiAiB

Reputation: 14122

// Create the global, and also give ourselves a convenient alias for it (`mod`)
var mod;
window.MyModule = mod = {
    RED: "#FF0000",
    BLUE: "#0000FF",
    // ...
    GREEN: "#00FF00"
};

or if you want to spare typing time:

var cols = mod.COLORS;
cols.RED;

Upvotes: 2

Related Questions