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();
}


Leave a reply
You can use Markdown in your comment as well as plain HTML. You can use
<filter:jscode lang="ruby">and</filter:jscode>tags to surround code blocks (supported languages are css, html, javascript and ruby). Your email address will not be published.If your comment doesn’t appear immediately after posting it could have been marked as spam. Don’t worry: we regularly check for and approve incorrectly filtered comments so you shouldn’t have to wait too long for it to be shown.