HTML and CSS Reference
In-Depth Information
this.listeners = this.listeners || {};
this.listeners[event] = this.listeners[event] || [];
this.listeners[event].push([ target || this, callback]);
if(target) {
if(!target.binds) { target.binds = []; }
target.binds.push([this,event,callback]);
}
},
At its base, the
bind
method is relatively straightforward: The only pieces of essential code are the three
lines in the center that add a listener to an object, called
this.listeners
, keyed by the name of the event.
Each listener consists of a two-element array made up of a context object and the callback itself. The code first
needs to check that the
this.listeners
array exists because
Evented
doesn't have an
init
constructor
method.
The rest of the code is in line with Quintus's goal of being friendly to developers by enabling a few different
input formats. The
bind
method can be called three different ways:
scene.bind('start',function() { ... });
scene.bind('start',player,function() { ... });
scene.bind('start',player,'methodName');
The first signature is useful when you don't need to worry about context or objects unbinding themselves
when they are removed from the game. The latter two both provide the same result, but one takes a string for
the name of the method property on the target object, and the other takes the method itself.
Next consider the
trigger
method, the simplest method of the four. Fill the method in with the code from
Listing 9-10
.
(Don't forget to separate each of the four method definitions with a comma.)
Listing 9-10:
Evented trigger method
trigger: function(event,data) {
if(this.listeners && this.listeners[event]) {
for(var i=0,len = this.listeners[event].length;i<len;i++) {
var listener = this.listeners[event][i];
listener[1].call(listener[0],data);
}
}
},
trigger
just checks to see if there are any listeners listening to that specific event. If so, each of the listen-
ers is looped over, and the callback is called with the provided context. Because each listener is made up of an
array with the context and callback, the code for actually making the call looks like this:
listener[1].call(listener[0],data);
Given the flexibile notion of context and the
this
object in JavaScript, you should always be explicit with
what the context of a method call is.
With events bound and triggerable, you can unbind them when an object is destroyed or no longer needs to
Listing 9-11:
Evented unbind method
unbind: function(event,target,callback) {
if(!target) {