April 25, 2007

ActionScript Delegate

In ActionScript there is an object you can use for passing references to members functions of a class called Delegate. This is useful for associating event listeners to a method on an instance of a class rather than a static:


function hookEvent(element)
{
element.onSelectionChange = Delegate.create(this, this.on_change);
}

function on_change() // <-- note: not a static
{
// do stuff
}

Using this helps a lot with your code organization. This pattern is also available in javascript though it's slightly more arcane:

setTimeout((function() {this.sendPoll()}).bind(this), this.options.timeout);