Thursday, August 2, 2007

Event.bubbles, Event.cancelable, and Event.currentTarget

original author : Ruben Swieringa

source: Ruben Swieringa's blog

== some quote for mhis blog ==
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.

=====
you can also find a great example on his blog.

1 comment:

Unknown said...

Hey Feng, nice post, although you forgot to include the links that I had in my post, could that have occured when you copied and pasted it from mine?
Also, in my original post I had an example which you forgot to include..
Thought you might want to know..

Kind regards, Ruben Swieringa

PS. Here's the link:
rubenswieringa.com/blog/eventbubbles-eventcancelable-and-eventcurrenttarget