vendredi 18 décembre 2015

JavaScript Event notifications from sub modules

Current using revealing module pattern for the top module. The main JS module provides interface for the apps to register for events. Now the library has sub modules with namespaces.

For eg:

Main = (function() {
    function on(event, fn) {
        ....;
    }
}());

Main.level1 = (function() {
    function level1() {
    }

    level1.prototype.dothis = function() {
        ....;
    }

    return level1;
}());

And one more sub-sub-module as below

Main.level1.level2 = (function() {
    function level2() {
    }

    level2.prototype.dothis = function() {
        ....;
    }

    return level2;
}());

Now if the code in sub module level2 wants to emit/fire an event, how can this be done? An in-elegant way would be for the Main module and the sub-module level1 to expose a public api which will be called by level2 whenever it wants to emit an event to application. But this is really a bad way to design the library/module. Is there a better way to do this?

Aucun commentaire:

Enregistrer un commentaire