CoreJS.MethodRefsAndEvents

Method References

A method reference is a reference to a method of a specific object instance. This construct is used enable object-oriented events in JavaScript, such that an event listener can be registered on a method of an instance, rather than only on a global method.

To create a method reference, a "MethodRef" object is instantiated. The constructor of MethodRef takes two parameters, a reference to an object, and a reference to the method. This typically takes the following syntax:

new Core.MethodRef(this, this.method)

Calling the invoke() method on a method reference will cause the method to be invoked. The 'this' pointer will be set appropriately on invocation, such that the method will behave correctly as though it is associated with its instance object.

Events

CoreJS provides an event management, Core.ListenerList system that can allows for the registration of MethodRefs as event listeners. When an event is fired from a Core.ListenerList to its listeners, any MethodRef-based listeners are invoked using the invoke() method, such that the 'this' pointer refers to their parent object.

The following example demonstrates object-oriented event listeners and method references:

Core.extend({

    $construct {
        this.randomNumber = parseInt(Math.random() * 100);
        var button = new EchoApp.Button();
        button.addListener("action", new Core.MethodRef(this, this.doAction));
    },

    doAction: {
        alert("My random number is: " + this.randomNumber);
    }
});

The EchoApp.Button object, as a result of being derived from EchoApp.Component, provides an addListener method that installs a listener into a Core.ListenerList. When the button is clicked, an event will be fired through that Core.ListenerList. As a result, the doAction() method registered as a listener in the above example will be invoked correctly, with the 'this' pointer set correctly.

last edited 2007-10-31 03:43:21 by TodLiebeck