Custom broadcast events in AS3?
In Actionscript 3, most events use the capture/target/bubble model, which is pretty popular nowadays:
When an event occurs, it moves through the three phases of the event flow: the capture phase, which flows from the top of the display list hierarchy to the node just before the target node; the target phase, which comprises the target node; and the bubbling phase, which flows from the node subsequent to the target node back up the display list hierarchy.
However, some events, such as the Sprite class's enterFrame
event, do not capture OR bubble - 开发者_运维百科you must subscribe directly to the target to detect the event. The documentation refers to these as "broadcast events." I assume this is for performance reasons, since these events will be triggered constantly for each sprite on stage and you don't want to have to deal with all that superfluous event propagation.
I want to dispatch my own broadcast events. I know you can prevent an event from bubbling (Event.bubbles = false
), but can you get rid of capture as well?
The answer from back2dos is wrong. Actually Event.bubbles
property does not affect capture phase.
public class CaptureTextInput extends Sprite
{
function CaptureTextInput()
{
var t:TextField = new TextField();
t.type = TextFieldType.INPUT;
addEventListener(TextEvent.TEXT_INPUT, function(event:TextEvent):Void
{
trace("captured"); // This event will be triggered properly when you type in text field.
}, true);
addChild(t);
}
}
bubble and capture phase are both parts of the whole bubbling mechanism. if bubbles
is set to false
, both are non-existent.
If you get rid of the bubble and capture phases, that doesn't make it a broadcast event. What's special about broadcast events is that when one is dispatched, every listener is triggered regardless of where they are on or off the display list. If there's a way to dispatch your own broadcast events, I don't know what it is.
精彩评论