Menu

Ruben Swieringa on Actionscript and a whole lot of other stuff..

Perhaps some of you may not know this, but event-bubbling in Actionscript3.0 is way cool and well worth your attention. So read on.

With event-bubbling you can let one Event subsequently call on every ancestor (containers of containers of etc.) of the DisplayObject that originally dispatched the Event, all the way up to the surface (read: Stage), hence the name ‘bubbling’.
Perhaps noteworthy is that bubbling for an Event instance is disabled by default, and can only be activated by setting the bubbling parameter in the Event constructor.

Although the documentation doesn’t seem to make it all too apparent, event-bubbling is actually the reason why the Event class has a currentTarget property (as well as a target property).
So what is the use of Event.currentTarget? While the target property will always have its value set to the DisplayObject that originally dispatched the Event, the currentTarget property always points to the DisplayObject that the event is currently processing (i.e. bubbling at).

Now, you will probably not always want your Event to bubble all the way up to the Stage of your movie. This is where the cancelable property comes into the picture.
Setting the cancelable property contructor-parameter to true allows you to call the stopPropagation() and stopImmediatePropagation() methods later on. Both methods basically abort the bubbling process.
The difference here is that the latter also aborts execution of other listeners for the same Event-type on the same currentTarget, whereas the former only aborts execution of listeners to subsequent targets.

The following example attempts to visualize the concept of event-bubbling in AS3. Click the big button in the middle to dispatch a bubbling Event, and tick the CheckBoxes to have that Event canceled at a specific parent of the Button. Right-click to view source.
[kml_flashembed movie=”http://www.rubenswieringa.com/blog/wp-content/uploads/2007/flexeventbubbling/main.swf” height=”400″ width=”350″ /]

Comment navigation

What happends if I’m having the exact opposite behavior? I have a MovieClip with other MovieClips inside. I add a ‘MouseOver’ EventListener to my Parent MovieClip, and that event is being triggered on his children movieClips too. How can I avoid the event to be passed to the children?