Resurrecting Actionscript's 'Delegate.create' for function binding in AS3

Derek Wischusen showed a cool technique for simulating Ruby's Mixin's in Flex here. I started trying it out and was loving it until I found out some details about event listeners that were show-stoppers for me. Well, after learning more about Prototype recently (with it's very closely related javascript/ecmascript) I solved the problem and am throwing this code up here in case anyone else finds it useful.

The Problem

Derek's code allows you to add code to your classes by 'mixing' in other code. One way to add this 'other code' is by adding functions to the prototype. (see Derek's post for details) Unfortunately however, when functions are added in this way and used as event listeners, the 'this' keyword inside the function will refer to the global object instead of the object you meant it to be attached to. (see 'Programming Actionscript 3.0' pg 361 This means that your listener function becomes essentially static to you and can't reference all the data you want it to.

The solution, it turns out, is to resurrect Mike Chamber's old idea of Delegate.create. This static method was used like so:

myComboBox.addEventListener("change", Delegate.create(this,onMyComboBoxChange));

And it ensured that when 'onMyComboBoxChange' was called, the 'this' keyword would refer to the 'this' from the 'create' call (or whatever obejct you placed there). Delegate.create was apparently dropped in ActionScript 3.0 because they thought we didn't need it anymore (because they added method closures which are automatically bound to their object and they don't like using the prototype anymore I guess, silly them).

However, since actionscript anonymous functions are closures, you can do the same thing that the Prototype framework does (which almost the exact same code) to add a 'bind' method to the Function class so that you can get the same result as above with this code:

myComboBox.addEventListener("change", onMyComboBoxChange.bind(this));

Viola! Back to the land of having fun with Derek's mixin class.

Here is the code (someday I will extend it to be more general like Prototype's code, but for now all I need it for is simple event listeners):

Function.prototype.bind = function():Function {
  var __method:Function = this;
  var object:Object = arguments[0];
  return function():void {
    __method.apply(object, arguments);