Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Callbacks as object properties

Tags:

javascript

I would like to get a similar functionality to this:

function foo(before, after){

    before();

    setTimeout(function(){
         after();
    },100)
}

foo(function(){
    console.log('before');
}, function(){
    console.log('after');
});

When returning an object instead of using callbacks (psuedo code):

var foo = function() {

     before();         

     setTimeout(function(){
         after();
     },100)

     return {
         before: before,
         after: after
     }
};

foo().before(function(){
    console.log('before');
});

foo().after(function(){
    console.log('after');
});

Or perhaps even

foo().before(function(){
    console.log('before');
}).after(function(){
    console.log('after');
});

Is this possible?

like image 541
Johan Avatar asked Dec 10 '25 21:12

Johan


1 Answers

Yes, your function can return an object with before and after methods that keep track of which callbacks has been set, and when both are set it can call them:

function foo() {

    var beforeFunc = null, afterFunc = null;

    function activate() {
        beforeFunc();
        window.setTimeout(afterFunc, 100);
    }

    var obj = {
        before: function(f) {
            beforeFunc = f;
            if (afterFunc != null) activate();
            return obj;
        },
        after: function(f) {
            afterFunc = f;
            if (beforeFunc != null) activate();
            return obj;
        }
    };

    return obj;

}

// As both callbacks need to be set, the order is not important
foo().after(function(){
    console.log('After');
}).before(function(){
    console.log('Before');
});

Demo: http://jsfiddle.net/4HypB/

like image 97
Guffa Avatar answered Dec 13 '25 10:12

Guffa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!