简体   繁体   中英

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 */

});

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.

This is one of the most complete callback functions that i saw. So the answer is no, this is one of the best.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM