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!
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...orcallback.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…:But there’re so many optional parameters…
Another thing is the check which you are doing:
is not actually necessary, this is enough:
typeof callback === 'function'The first condition will return
falseonly ifcallbackis evaluated tofalsebut if it’s evaluated tofalsetypeof callbackwont returnfunction. 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! 🙂