Event Bubbling (事件浮升机制)
ok,我姑且这么称呼Event Bubbling吧.原来Ralf在自己的Blog上发表了在As2.0中使用Event Bubbling的方法.实在是个有创意的想法.
Event Bubbling原本是只能在AS3.0中使用的.在Event Bubbling机制里面,产生事件的对象首先会收到事件。然后,事件会依照对象的等级结构向上传播.那么简单的说在Flash中的使用Event Bubbling则是使处理嵌套的MC显得简单很多.Event Bubbling的使用主要便是很好的加强了事件处理的连续性.
Ralf的方案是用自己的方法来替换dispatch的方法,下面这段方法是Ralf的一个范例,你也可以自己修改:
publicstaticinitializeBubbling(dispatcher:MovieClip){
varparentDispatcher=dispatcher._parent;//addtraversaloptionally,seecommentsbelow
varoldDispatchEvent=dispatcher.dispatchEvent;
dispatcher.dispatchEvent=function(evt){
oldDispatchEvent.call(dispatcher,evt);
if(evt.bubbles){
parentDispatcher.dispatchEvent(evt);
}
}
}
更详细的文章,我想还是看原文比较好
同时,Peter Elst也写了一个使用的范例.
比如,当你不使用Event Bubbling时,你需要通过以下的方法来让mc1.mc2广播事件.
mc1.mc2.addEventListener("someEvent",someEventHandler);
如果使用EventBubbling则可以这样.
mc1.addEventListener("someEvent",someEventHandler);
由于这样的事件链机制,你就不用担心时间出自哪里了.
importmx.events.EventDispatcher;
//RalfBokelberg’sAS2.0eventbubblingworkaround
initializeBubbling=function(dispatcher:MovieClip){
varparentDispatcher=dispatcher._parent;
varoldDispatchEvent=dispatcher.dispatchEvent;
dispatcher.dispatchEvent=function(evt){
oldDispatchEvent.call(dispatcher,evt);
if(evt.bubbles){
parentDispatcher.dispatchEvent(evt);
}
}
}
//createemptymovieclips
varmc1:MovieClip=createEmptyMovieClip("mc1",1);
varmc2:MovieClip=mc1.createEmptyMovieClip("mc2",1);
//initializeEventDispatcher
EventDispatcher.initialize(mc1);
EventDispatcher.initialize(mc1.mc2);
//initializeeventbubbling
initializeBubbling(mc1.mc2);
//addeventlistenerstomovieclips
mc1.mc2.addEventListener("customEvent",function(){
trace("customEventcapturedbymc1.mc2");
});
mc1.addEventListener("customEvent",function(){
trace("customEventcapturedbymc1");
});
//dispatchevent
mc1.mc2.dispatchEvent({type:"customEvent",bubbles:true});