Search code examples
javascriptfunctionobjectliteralschain

How can I call any function in a chain of functions, without the chaining?


Sorry if my question wasn't clear enough. I'll put my code here...

var chain = {
    'fn_1' : {
             //fn_1 code here
             chain.fn_2();},
    'fn_2' : {
             //fn_2 code here
             chain.fn_3();}

...and so on
}

Let's say if i wana call chain.fn_1(), is there a way I can do that without calling chain.fn_2()?

What I can think of right now is a flag, but that would be alot of excess flags probably for each function. Do you guys have any ideas?


Solution

  • var chain = {
        fn : ['fn1', 'fn2', 'fn3'],
        call : function(name) {
           var i = 0, pos = -1, l = this.fn.length;
            for(i = 0; i < l; i += 1) {
                if(this.fn[i] == name) {
                    pos = i;
                }
                if(pos !== -1) {
                    this[this.fn[i]]();             
                }
            }
    
        },
        fn1 : function() {
            alert('fn1');
        },
        fn2 : function() {
            alert('fn2');
        },
    };
    chain.call('fn1'); //chain
    chain.fn1(); //single