Best practice for repeating callback functions?

callback, dry, function, javascript, jquery

Solution

In my opinion it's not necessary to have a callback handler. In different situations you may need to call the callback with different context (for example `callback.call(ob...` or `callback.apply(obj...`). So you will need an extra parameter of the callback handler (the context). Another thing that isn't very pleasantly is that you may need to pass custom arguments to the callback. With the callback handler you can make the pain smaller by passing all the parameters into an array and applying the function on them. Something like...:

function callbackHandler(callback, arguments, context) {
    if (typeof callback === 'function') {
        return callback.apply(context, arguments);
    }
    return null;
}

But there're so many optional parameters... Another thing is the check which you are doing:

if (callback && typeof callback === 'function') //notice that typeof is an operator not a function, so you don't need parentless

is not actually necessary, this is enough: `typeof callback === 'function'`

The first condition will return `false` only if `callback` is evaluated to `false` but if it's evaluated to `false` `typeof callback` wont return `function`. So the condition is short enough.

That's why I think that you don't need a callback handler. And by the way nice question I love such topics! :-)

Problem

In my code I use a lot of (named) callback functions, just to give a quick example: ``` function showThis(callback) { // Do something if (callback && typeof(callback) === 'function') { callback(); } } ``` Now I have this pattern repeat throughout different functions (I'm talking about the callback part), so is it considered to be better if I make one generic callback handler function and include that? Something like: ``` function doCallback(callback) { if (callback && typeof(callback) === 'function') { callback(); } } function showThis(callback) { // Do something doCallback(callback); } ``` I would think that's better to keep code DRY, but I'm unsure. Any help is greatly appreciated!

Original source