From InsideRIA.
Flex does not provide a way to temporarily disable event listeners and re-enable them later. You may want to do this to prevent endless loops. For example, when some code modifies the selectedIndex of a List, an event is fired. If you have a listener that reacts to the event, you may need a way of suppressing the listener’s response under certain conditions. You have two choices:
* Couple the listener to the code that generates the event, so it knows when to ignore the event. This defeats one of the purposes of event-driven programming, separation of concerns.
* Suppress the event dispatch
My gift to you today, dear reader, is the EventManager class. This class remembers all event listeners assigned to an EventDispatcher, and can remove or re-instate those listeners with a single method call.
package events {
import flash.events.EventDispatcher;
public class EventManager {
private var dispatcher:EventDispatcher;
private var type:String;
private var listener:Function;
private var useCapture:Boolean;
private var priority:int;
private var useWeakReference:Boolean;
public function EventManager(dispatcher:EventDispatcher, type:String, listener:Function, useCapture:Boolean, priority:int, useWeakReference:Boolean) {
this.dispatcher = dispatcher;
this.type = type;
this.listener = listener;
this.useCapture = useCapture;
this.priority = priority;
this.useWeakReference = useWeakReference;
}
private static function disableFn(item:*, index:int, array:Array):void {
var em:EventManager = EventManager(item);
em.dispatcher.removeEventListener(em.type, em.listener, em.useCapture);
}
public static function disableAll(listeners:Array):void {
listeners.forEach(disableFn);
}
private static function enableFn(item:*, index:int, array:Array):void {
var em:EventManager = EventManager(item);
em.dispatcher.addEventListener(em.type, em.listener, em.useCapture, em.priority, em.useWeakReference);
}
public static function enableAll(listeners:Array):void {
listeners.forEach(enableFn);
}
}
}
package {
public class EMDemo extends ComboBox {
private var listeners:Array = new Array();
override public function addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void {
super.addEventListener(type, listener, useCapture, priority, useWeakReference);
listeners.push(new EventManager(this, type, listener, useCapture, priority, useWeakReference));
}
/** Prevent update events from being issued */
public function quietlySetIndex(newIndex:int):void {
EventManager.disableAll(listeners);
selectedIndex = newIndex;
EventManager.enableAll(listeners);
}
}
}