Any class involved in bubbling must extend DisplayObjectContainer. Sprite is the most basic DisplayObjectContainer class and most examples I see use it, so that's what I will use. I gave a brief overview of how event bubbling works in the Flex example that I won't repeat here.
I'm creating three classes that include each other. The primary class includes Level1. Level1 includes Level2. Level2 includes Level3. Level3 triggers an event when it's added to the stage. The event from Level3 will bubble through Level2 and Level1 to the primary class without re-dispatching it.
event_bubbling_as.as
package { import flash.display.Sprite; import flash.events.Event; import obj.Level1; import obj.Level3; public class event_bubbling_as extends Sprite { private var _level1:Level1 public function event_bubbling_as() { _level1 = new Level1; _level1.addEventListener(Level3.EVENT, onEvent); addChild(_level1); } private function onEvent(event:Event) : void { trace('caught event from level 3'); } } }Level1.as
package obj { import flash.display.Sprite; public class Level1 extends Sprite { private var _level2:Level2; public function Level1() { trace("in level 1"); _level2 = new Level2; addChild(_level2); } } }Level2.as
package obj { import flash.display.Sprite; public class Level2 extends Sprite { private var _level3:Level3; public function Level2() { trace("in level 2"); _level3 = new Level3; addChild(_level3); } } }Level3.as
package obj { import flash.display.Sprite; import flash.events.Event; public class Level3 extends Sprite { public static const EVENT:String = "level3"; public function Level3(){ trace("in level 3"); //trigger event when the object is added to the stage addEventListener(Event.ADDED_TO_STAGE, launchEvent); } public function launchEvent(event:Event) : void { var newEvent:Event = new Event(EVENT, true, true); dispatchEvent(newEvent); } } }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.
Really useful, thanks.
ReplyDeleteGreat, this helped me to understand how I could bubble up events more than 1 level.
ReplyDeleteI have reviewed your Web site and has very good resources like this one. Thanks to put at the disposal of all these subjects
ReplyDeleteHey! A Wonderful Example. Looking forward to use this method.I am afraid, How I can use it to greate extend
ReplyDeleteThank You! I got it to work.
ReplyDeleteSusana
Thanks a lot! I learned a lot from it. I already knew how to make custom events, but haven't tried listening for an event in another class. Now I understand more of this thanks to your tutorial.
ReplyDeleteThanks a lot. I really needed this in my projects. Now I understand it clearly. This is the most simple and easy to understand bubling sample among others in the internet.
ReplyDelete