In Javascript
You'll have to know how to program object oriented with Javascript. Read the articles at Webreference (links at the left of the article) to catch up on that.
10/16/2005; 1:23:17 AM
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 problem is as follows: Methods use this
to refer to the object it is
a method of. But, when using a method as event handler or callback function,
this
does no longer point to that object. The trick is to use the closure like
behaviour of functions, so that the method will always have access to it's object.
Let's look at an example: We want to use a method of an Alerter class as an event handler.
So, instead of using this
, we use a variable me
, that
equals this
when the invoke
method is created. And, in contrast
to this
, me
will keep refering to the correct
Alerter
object, even when it's passed as a function to the attachEvent
method of an HTML element.
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.
Now we can write:
With the andThen
method, it becomes very easy to create an object that
allows several other objects to register callbacks.
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.