Mar
Mar

Reputation: 1606

How to fire multiple namespace functions at once?

Is it possible to execute all the functions of a namespace with one call?

Exp:

var myApp = { 

    e : $('.js-box'),
    addStyle : function(){
    myApp.e.css('height','200');
    },
    warn : function(){
    alert('WOOOOOoooOO');
    }  
};
myApp.addStyle();
myApp.warn();

It works correct with the code above..

Can we fire addStyle and warn functions with one call?

What I have tried/thought:

var myApp = { 
    workAll : function(){
        e : $('.js-box'),
        addStyle : function(){
        myApp.e.css('height','200');
        },
        warn : function(){
        alert('WOOOOOoooOO');
        }
    }    
};
myApp.workAll();

this doesn't work anything.. How can I do something like that?

Live try: http://jsfiddle.net/C7JJM/82/

Thank you in advance!

Upvotes: 0

Views: 60

Answers (3)

Navneet
Navneet

Reputation: 447

var myApp = { 
     e : $('.js-box'),

        addStyle : function(){
        myApp.e.css('height','400');
        },
        warn : function(){
        alert('WOOOOOoooOO');
        }  ,
    addstyleall:function(){this.addStyle();this.warn();}

};
myApp.addstyleall();

Upvotes: 0

myuce
myuce

Reputation: 1391

try this one

    //http://stackoverflow.com/questions/5999998/how-can-i-check-if-a-javascript-variable-is-function-type
    function isFunction(functionToCheck) {
     var getType = {};
     return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
    }

    function executeAll(ns){
        if(ns){
        for (property in ns) {
                if (ns.hasOwnProperty(property)) {
                    var p = ns[property];
                    if (p != null && isFunction(p)) {
                        p();
                    }
                }
            }
        }
    }
   var myApp = { 

            e : $('.js-box'),
            addStyle : function(){
            myApp.e.css('height','200');
            },
            warn : function(){
            alert('WOOOOOoooOO');
                }  
    };
    executeAll(myApp)

But beware of the argument passed to the functions

http://jsfiddle.net/s8ng608f/1/

Upvotes: 0

Rahul
Rahul

Reputation: 5774

Auto calling all the functions looks difficult without making each function self invoking. But with custom caller, it is pretty much possible.. Just add another function called workAll in your first function which is working..

var myApp = { 

        e : $('.js-box'),
        addStyle : function(){
            console.log("Add style called");
            myApp.e.css('height','200');
        },
        warn : function(){
            alert('WOOOOOoooOO!!!');
        },
        runAll : function(){
            this.addStyle(); //call AddStyle
            this.warn(); //call Warn
        }
};
myApp.runAll();

Demo here :

http://jsfiddle.net/C7JJM/84/

Upvotes: 1

Related Questions