The familiar format we've used for event listeners includes five parameters.
//btn.addEventListener(eventType, listenerFunction, useCapture, priority, // useWeakReference); btn.addEventListener(MouseEvent.CLICK, onBtnClick, false, 0, true);
The first and second parameters are mandatory, and are the event type and function that is called when the listener is triggered. The third, fourth, and fifth parameters are optional. The third determines the event phase used (see "Event Phases in Action" for more information), and the last specifies whether or not a weak reference is used (see "Garbage Collection" on page 47 of the book for more information).
The fourth parameter, however, is an integer that sets the priority of the listener. Because a single object can use multiple listeners for the same event, it is sometimes useful to specify the order in which the similar listeners are executed.
The default value for the priority parameter is 0. If the optional parameter is omitted, all listeners will have a value of 0 and events will be handled in the order in which they were added. If unique integers are used, the listener with the highest priority will be executed first, and so on down the line.
The below code snippet uses the priority parameter to execute the events in the opposite order in which they were added:
-
var btn:Sprite = new Sprite();
-
btn.graphics.beginFill(0);
-
btn.graphics.drawCircle(0,0,10);
-
btn.x = btn.y = 100;
-
addChild(btn);
-
-
btn.addEventListener(MouseEvent.MOUSE_DOWN, onPriority0, false, 0);
-
btn.addEventListener(MouseEvent.MOUSE_DOWN, onPriority1, false, 1);
-
btn.addEventListener(MouseEvent.MOUSE_DOWN, onPriority2, false, 2);
-
-
function onPriority0(evt:Event):void {
-
trace("priority 0 event");
-
}
-
-
function onPriority1(evt:Event):void {
-
trace("priority 1 event");
-
}
-
-
function onPriority2(evt:Event):void {
-
trace("priority 2 event");
-
}
This will trace:
priority 2 event priority 1 event priority 0 event
While it is not common for objects to have multiple listeners listening for the same event, if that need arises, you can still control their execution order using the priority parameter. For example, you may require that an initialization routine execute prior to another function. We'll revisit this topic again in future posts, so check back periodically if you're interested in this topic.
Print This Post

































0 Responses to “Event Listener Priority”
Leave a Reply