Event Handlers and Callback Functions in JavaScriptby: Sjoerd VisscherIntroduction In Higher Order Programming in Javascript I discussed the various ways of using functions as values. One particular trick in that document caught the attention of Dan Shappir, who pointed out to me: "your technique shows how JavaScript supported delegates all along, so this is not some great C#/.NET invention." While searching for some more information about these delegates, I found out that Microsoft has added them to Visual J++ too, invoking an interesting response from Sun, where it's discussed how delegates can much better be implemented with Inner Classes. As this is aparently a hot issue in other languages, and because event handlers and callbacks are useful in webpages too, I decided to write a new article to discuss this. The Trick The problem is as follows: Methods use Let's look at an example: We want to use a method of an Alerter class as an event handler. function Alerter(text) {
So, instead of using Higher Order Programming again
var sayHi=new Alerter('Hello, world!');
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) {
Now we can write: setTimeout((sayHi.invoke).andThen(sayBye.invoke),2000); Several callbacksWith the function Manager() {
Conclusion With a simple technique event handlers and callback functions become a lot more interesting in Javascript. As Dan Shappir pointed this out to me, just this morning (after which I started to write the article), I can't wait to try more of this. I hope you can't too, and if you've got something to show, don't hesitate to contact me. © 2008 NetVisits, Inc. All rights reserved. |