flash event_model_subtleties
Subtleties
In ActionScript 1 and 2 we were used to adding listeners that weren’t functions but objects. In reality a method with an event name was triggered when it was broadcast. To listen to a keyboard activated event would give us the following code:
var myListener = new Object(); myListener.onKeyDown = function ( ) { trace ( Key.getCode() ); } Key.addListener ( myListener );
By making the object a listener, we define a method carrying the name of the broadcast event; the player therefore triggers a method when the event is broadcast. From now on only a function or a method can be made into a listener.
The following code gives a compilation error:
var myListener:Object = new Object(); stage.addEventListener ( KeyboardEvent.KEY_DOWN, myListener );
Displaying the following message in the output window:
1118: Implicit constraint of a static Object value to a type, potentially without a Function correlation.
The compiler detects that the object type used as a listener is not a function but an object and refuses the compilation. On the other hand, it is possible to make a dynamically-made method on an object as a listener and not a function.
The following code works without any problems:
var myListener:Object = new Object(); myListener.myMethod = function () { trace( "keyboard key pressed" ); } stage.addEventListener ( KeyboardEvent.KEY_DOWN, myListener.myMethod );
A small thing to note in this case is that the execution context of the myMethod method is not that which we are expecting. When calling the keyword this to display the current context we are surprised to not get [object Object] but [object global].
When we put a method in the dynamic property of an object, the Flash player has no way to attach the method to its original object; the function therefore executes the global object in the global context. The following code shows this point in context:
var myListener:Object = new Object(); myListener.myMethod = function () { // displays : [object global] trace( this ); } stage.addEventListener ( KeyboardEvent.KEY_DOWN, myListener.myMethod );
It is therefore strongly advised to avoid this technique to manage events in your application.
In this chapter we have learned about the new event model, in order to totally cover mechanisms linked to this model we will now look at the management of display in ActionScript 3.
Worth remembering
- If you add a listener with the help of a weak reference it will be deleted from the memory even if it has not been unsubscribed from the removeEventListener method.
Mediabox Training Centre © 2000 - 2008 All rights reserved.
Adobe Authorized Training Centre. State convention under number 25 14 02167 14.
Mediabox : SARL au capital de 62.000€ - Activity number: 25 14 02167 14 - SIRET : 493 716 468 00027
MEDIABOX, 102 Avenue des Champs Elysées, 75008 PARIS - Tel. +33(0)2.31.91.96.89 - Fax. +33(0)2.72.68.56.42


