Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Self-Executing Anonymous Modules

Tags:

javascript

Expanding on this answer I would like to know how to create new modules that belong to the same namespace (PROJECT).

A.init(); -- will become --> PROJECT.A.init();

Modules

(function( A, $, undefined ) {
    A.init = function() {
        console.log( "A init" );
    };   
}( window.A = window.A || {}, jQuery ));

(function( B, $, undefined ) {
    B.init = function() {
        console.log( "B init" );
    };   
}( window.B = window.B || {}, jQuery ));

A.init();
B.init();

http://jsfiddle.net/sKBNA/

like image 321
howtodothis Avatar asked Oct 22 '22 09:10

howtodothis


1 Answers

Just insert the additional namespace into the property chain:

// create top namespace
window.PROJECT = window.PROJECT || {};

// stays the same
(function( A, $, undefined ) {
    A.init = function() {
        console.log( "A init" );
    };
// except for the last line:
}( window.PROJECT.A = window.PROJECT.A || {}, jQuery ));

// same for the B (sub)namespace:
(function( B, $, undefined ) {
    …  
}( window.PROJECT.B = window.PROJECT.B || {}, jQuery ));

// and of course add it at the invocations:
PROJECT.A.init();
PROJECT.B.init();
like image 175
Bergi Avatar answered Nov 02 '22 08:11

Bergi