Here is some example code I made in MXML that shows how event bubbling works. There are four files. The Application file includes Layer1. Layer1 includes Layer2. Layer2 includes Layer3. When Layer3 is created it will throw an event. The first property of the event is the string that will trigger event listeners, the second allows the event to bubble through the DisplayObject tree. The third allows the event to be canceled at any of the DisplayObjects it passes through. The event will bubble through each DisplayObject and back to the Application without manually passing it forward.
UPDATE
If you're looking for an example of event bubbling in ActionScript please view this article.
index.mxml
<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" initialize="init()" styleName="plain"> <mx:Script> <![CDATA[ import obj.Level3; import obj.Level1; private var _level1:Level1; private function init() : void { trace("in the base"); _level1 = new Level1; //add eventListener _level1.addEventListener(Level3.EVENT,onEvent); addChild(_level1); } private function onEvent(event:Event) : void { trace("picked up event from Level3 "); } ]]> </mx:Script> </mx:Application>
Layer1.mxml
<?xml version="1.0" encoding="utf-8"?> <mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" width="400" height="300" initialize="init()"> <mx:Script> <![CDATA[ private var _level2:Level2; private function init() : void { trace("in level 1"); _level2 = new Level2; addChild(_level2); } ]]> </mx:Script> </mx:Canvas>
Layer2.mxml
<?xml version="1.0" encoding="utf-8"?> <mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" width="400" height="300" initialize="init()"> <mx:Script> <![CDATA[ private var _level3:Level3; private function init() : void { trace("in level 2"); _level3 = new Level3; addChild(_level3); } ]]> </mx:Script> </mx:Canvas>
Layer3.mxml
<?xml version="1.0" encoding="utf-8"?> <mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" width="400" height="300" initialize="init()"> <mx:Script> <![CDATA[ public static const EVENT:String = "level3"; private function init(): void { trace("in level 3"); var event:Event = new Event(EVENT,true,true); dispatchEvent(event); } ]]> </mx:Script> </mx:Canvas>
You can download the Flex Project Archive example here. This can be directly imported into Flex. Run it in debug mode to see how each level is triggered.
Very nice example, thanks!
ReplyDeleteGood articles and thanks for sharing! But it's so weird that you blog is in a mess through my new Firefox. I dont think it's my explore problem? Beacuse it's pretty normal when visit other websites.Cool, i am impressed with the views there, it is really a good idea to visit UK to enjoy our holiday!
ReplyDeleteBy Jordans 5
excellent example. thank's alot
ReplyDeletenice Example..
ReplyDeleteThe files are called Layer, but the objects are called Level, is this correct
ReplyDelete@bishoponvsto that's correct
ReplyDelete