Managing mutually exclusive overlays and popups efficiently in AS3
Here's a quickie for handling mutiple in-Flash popups or overlays that should all open exclusively (that is, if one is opened, all other should close) within an application in AS3.
A couple of classes, first one is the manager itself:
package {
import flash.display.Sprite;
public class OverlayManager {
private var objArray:Array;
public function OverlayManager() {
objArray = [];
}
public function registerOverlay(obj:Sprite):void {
objArray.push(obj);
obj.addEventListener(OverlayEvent.CHANGE, eChangeHandler);
}
private function eChangeHandler(e:OverlayEvent):void {
for (var i:uint = 0; i < objArray.length; i++) {
if (objArray[i] != e.object) objArray[i].close();
}
}
}
}
Next, our OverlayEvent:
package {
import flash.display.Sprite;
import flash.events.Event;
public class OverlayEvent extends Event {
public static const CHANGE:String = "change";
private var _object:Sprite;
public function OverlayEvent(type:String, $object:Sprite, bubbles:Boolean=false, cancelable:Boolean=false) {
super(type, bubbles, cancelable);
_object = $object;
}
public override function clone():Event {
return new OverlayEvent(type, object, bubbles, cancelable);
}
public override function toString():String {
return formatToString("OverlayEvent", "object", "type", "bubbles", "cancelable", "eventPhase");
}
public function get object():Sprite { return _object; }
}
}
And finally, an interface:
package {
public interface IOverlayObject {
function close():void;
}
}
Implementing involves a few quick steps for each object (obviously you'll need at least two for this to do anything). First, the object needs to implement the interface (basically requires a public close method on the object). Next, we need to register the object with the manager itself, and finally, whenever the object is shown, we need to dispatch an OverlayEvent.CHANGE event, passing along a reference to the open object. Example:
package {
import flash.display.Sprite;
import flash.events.MouseEvent;
public class OverlayObject extends Sprite implements IOverlayObject{
public function OverlayObject() {
}
public function close():void {
showObject(false);
}
public function showObject(show:Boolean):void {
if (show) dispatchEvent(new OverlayEvent(OverlayEvent.CHANGE, this));
visible = show ? true:false;
}
}
}



