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的一个范例,你也可以自己修改:
public static initializeBubbling(dispatcher:MovieClip){
var parentDispatcher = dispatcher._parent; //add traversal optionally, see comments below
var oldDispatchEvent = 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);
如果使用Event Bubbling则可以这样.
mc1.addEventListener("someEvent",someEventHandler);
由于这样的事件链机制,你就不用担心时间出自哪里了.
import mx.events.EventDispatcher;
// Ralf Bokelberg’s AS2.0 event bubbling workaround
initializeBubbling = function(dispatcher:MovieClip) {
var parentDispatcher = dispatcher._parent;
var oldDispatchEvent = dispatcher.dispatchEvent;
dispatcher.dispatchEvent = function( evt){
oldDispatchEvent.call( dispatcher, evt);
if( evt.bubbles){
parentDispatcher.dispatchEvent(evt);
}
}
}
// create empty movieclips
var mc1:MovieClip = createEmptyMovieClip("mc1",1);
var mc2:MovieClip = mc1.createEmptyMovieClip("mc2",1);
// initialize EventDispatcher
EventDispatcher.initialize(mc1);
EventDispatcher.initialize(mc1.mc2);
// initialize event bubbling
initializeBubbling(mc1.mc2);
// add event listeners to movieclips
mc1.mc2.addEventListener("customEvent",function() {
trace("customEvent captured by mc1.mc2");
});
mc1.addEventListener("customEvent",function() {
trace("customEvent captured by mc1");
});
// dispatch event
mc1.mc2.dispatchEvent({type:"customEvent",bubbles:true});