我希望我的类的父级首先处理事件,然后我想让子级处理事件。有没有办法明确地将事件搞砸了?我想做这样的事情:
...
this.addEventListener(MouseEvent.CLICK, characterClicked);
...
private function characterClicked(e:Event):void{
// pass event to parent to be handled first
...
}
这可能,如果是这样的话怎么样?
答案 0 :(得分:5)
事件有三个“阶段”; Capture, At target and Bubble。它们按此顺序出现,这意味着如果您将事件侦听器设置为处于捕获阶段,它将始终在一个常规集合之前触发(这意味着在目标或气泡处)。
像这样:
// in parent, third argument is "use capture"
child.addEventListener(MouseEvent.CLICK, handleClickInParent, true);
// in child, add listener as usual
addEventListener(MouseEvent.CLICK, handleClick);
现在,您的父事件侦听器将始终首先触发!
答案 1 :(得分:0)
我找到了一种方法来做到这一点。似乎是hackish,但它的确有效。如果有更好的方法,请告诉我。
...
this.addEventListener(MouseEvent.CLICK, characterClicked);
...
private function characterClicked(e:Event):void{
// pass event to parent to be handled first
this.removeEventListener(MouseEvent.CLICK, characterClicked); //prevent infinite loop
dispatchEvent(e); // send event to parent object
this.addEventListener(MouseEvent.CLICK, characterClicked);
e.stopImmediatePropagation();
...
}
答案 2 :(得分:0)
如果您要处理父级而非子级的侦听器,则可能更容易。然后你可以在完成后将事件传递给孩子:
// inside parent class:
childObj.addEventListener(MouseEvent.CLICK, onCharacterClicked);
private function onCharacterClicked(e:Event):void {
// do parent stuff first
// ...
// then pass event to child
childObj.onCharacterClicked(e);
}