0

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!

Mar
  • 1,526
  • 6
  • 21
  • 46

3 Answers3

1

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/

Rahul Patil
  • 5,656
  • 6
  • 37
  • 65
0

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/

myuce
  • 1,321
  • 1
  • 19
  • 29
0
var myApp = { 
     e : $('.js-box'),

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

};
myApp.addstyleall();
Navneet
  • 447
  • 4
  • 13