Helping ordinary people create extraordinary websites!
GET OUR NEWSLETTER
Your Email:
 

Event Handlers and Callback Functions in JavaScript

By Sjoerd Visscher
2006-08-19


Higher Order Programming again

window.setTimeout is an often used function for dynamic webpages. It waits for a given amount of time, and then calls a callback function. The above defined sayHi function can be used as a callback function: setTimeout(sayHi.invoke,2000) will show an alert box after 2 seconds. But what if we want to be extra cool and show 2 alert boxes after those 2 seconds? Then we'd have to create a new function that calls both Alerter objects:

var sayHi=new Alerter('Hello, world!');  

var sayBye=new Alerter('Bye, world!');
setTimeout(function() {sayHi.invoke();sayBye.invoke();},2000);

A nice feature of Microsoft's delegates is that you can create a single composite deligate from several delegates. It looks less messy than inserting an anonymous function. Let's do that in Javascript too, by extending the function prototype.

Function.prototype.andThen=function(g) {

var f=this;
return function() {
f();g();
}
};

Now we can write:

setTimeout((sayHi.invoke).andThen(sayBye.invoke),2000);

Several callbacks

With the andThen method, it becomes very easy to create an object that allows several other objects to register callbacks.

function Manager() {

this.callback=function () {}; // do nothing
this.registerCallback=function(callbackFunction) {
this.callback=(this.callback).andThen(callbackFunction);
}
}

var manager=new Manager();
manager.registerCallback(sayHi.invoke);
manager.registerCallback(sayBye.invoke);
manager.callback();


Tutorial Pages:
» Introduction
» The Trick
» Higher Order Programming again
» Conclusion


This article is licensed under the Creative Commons


 | Bookmark
Related Tutorials:
» JavaScript Debugging Techniques with Firebug
» Striped Tables Using JavaScript
» Opening PDFs in a New Window with JavaScript
» Essential Javascript -- A Javascript Tutorial
» Submit Forms Conditionally using JavaScript
» How to Setup a Randomising Function

Advertise with Us!


Tutorials Scripts Web Hosting Developer Manuals
Resources