We build Web & Mobile Applications.
Let’s say we have a JavaScript function that looks like this:
function plot(options) {
options = options || {};
this.onUpdate = options.onUpdate;
//
// more code to do something interesting
//
}
Here the plot
method allows an optional onUpdate
callback to be specified. The problem is that every time we should use the callback, we have to check that it was actually provided, like this:
if (typeof(this.onUpdate) == 'function') this.onUpdate();
Prototype provides the isFunction
method, which tidies up the code a little:
if (Object.isFunction(this.onUpdate)) this.onUpdate();
But I think a nicer way to handle this is to use the emptyFunction
method during the initialisation of the callback. emptyFunction
is pretty much what you’d expect: a function that’ll swallow any arguments you call it with, does nothing and returns nothing. This means that when we want to use the callback we can just call it without having to worry about whether or not we should, for example:
function plot(options) {
options = options || {};
this.onUpdate = options.onUpdate || Prototype.emptyFunction;
//
// more code to do something interesting
//
// Call the callback
this.onUpdate();
}