There's been a lot of hype around the support for event bubbling in AS3 recently, and after Ralf Bokelberg posted an ingenious method to get it to work with AS2.0 thought I'd look at it more closely and post an example.

First of all, what exactly is event bubbling? Well the concept is relatively easy, an event dispatched from a nested view 'bubbles' up the chain to its parent views so they can listen to and act upon that event. Without event bubbling the parent views need a reference to the nested view to listen to subscribe to the events.

Let's say we've got a movieclip mc1 that contains a nested movieclip mc2. When mc1.mc2 broadcasts an event, and you want to listen to it without event bubbling at your disposal you would write:

mc1.mc2.addEventListener("someEvent",someEventHandler); 

With event bubbling however you can simply use:

mc1.addEventListener("someEvent",someEventHandler);

as the event moves up the chain to parent movieclips and you don't need to care or know anything about where the event actually originates from.

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});

In the code snippet above you'll see Ralf's event bubbling workaround in action and the "customEvent" event dispatched by mc1.mc2 captured by mc1. If you set the bubbles property to false when you dispatch the event mc1 will no longer capture the event. That's pretty cool! You can see the advantages of not having to know anything about where the event comes from down the chain, if an event is broadcast and is set to bubble you'll catch it.

Posted
AuthorPeter
CategoriesFlash