Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Way To Create A Callback Function

Is there a better way than this to create a callback function for some random function ?

var showObj = function(obj,callback) {
    return setTimeout(function () {
        if(opts.centerObj == true) {
            var cssProps = getProps(obj);
            obj.css(cssProps).fadeIn('slow');
        }
            else {
                obj.fadeIn('slow');
            }
        if(typeof callback == 'function') {
            callback.call(this);
        }
    }, 1500);
}

The callback function doesn't have any parameter when I utilize it, I only do like this:

showObj(obj,function(){

/* Some Callback Function */

});
like image 625
Roland Avatar asked Jan 15 '12 10:01

Roland


1 Answers

I guess there is no particular 'bad' or 'wrong' way to invoke any (callback) method. You're doing just fine there, also checking for a function.

My only suggestion would be there, not to invoke the function with .call(). Unless you need to pass the current context just call callback();. That is, because .call() and .apply() invokations are up to 30% slower.

like image 122
jAndy Avatar answered Sep 25 '22 13:09

jAndy