Game Development Reference
In-Depth Information
This approach is typical in JavaScript development. Depending on the length and complexity of your function's
code, there will be times when you'll want to keep your handler function explicitly defined, but anonymous functions
can be handy for many reasons. Not only can they simplify the flow of your code for management and readability,
but they can also be crucial when managing scope in many situations.
As previously promised, you'll be diving deep into scope management as your games become more difficult,
but for now you can simply take a look at how you can obtain a reference to the object that triggered the event.
troll.addEventListener('click', function (e) {
stage.removeChild(e.target);
});
This approach uses the event object passed into the handler. This event object contains many properties that
can help you identify what was clicked and where on the stage, or on the object, the mouse pointer was when the
event was fired. You are able to kill the appropriate troll by using the target property in the event object, which is a
reference to the clicked display object.
You can similarly use the dblclick event to achieve the same effect for double-clicks. Listing 3-1 is an example
that uses this event to alert a message when the circle was double-clicked (see Figure 3-1 ).
Listing 3-1. Registering for Double-Click Events
var circle = new createjs.Shape();
circle.graphics.beginFill('#0000FF').drawCircle(0, 0, 50);
circle.x = stage.canvas.width / 2;
circle.y = stage.canvas.height / 2;
circle.name = 'Blue Circle';
stage.addChild(circle);
stage.update();
circle.addEventListener('dblclick', function (e) {
alert(e.target + ' was double clicked!');
});
 
Search WWH ::




Custom Search