Powerful Cancelable Events

When you dispatch events I bet that most Flash/Flex devs don’t take advantage of the fact that dispatchEvent returns a Boolean value indicating wether or not the event has been canceled. Normally your code looks similar to this:

var event:MyEvent = new MyEvent(MyEvent.FOO);
dispatchEvent(event)

If you want to let something only happen if the event wasn’t canceled it should look like this:

// The second "true" sets the event cancelable, first one sets bubbles
var event:MyEvent = new MyEvent(MyEvent.FOO, true, true);
if(dispatchEvent(event)){
   // do the actual task
}

With the code above the event listener can control if the actual task gets executed or not:

dispatchingInstance.addEventListener(MyEvent.FOO, fooHandler);
function fooHandler(event:MyEvent):void{
   // depending on what you want to achieve you can cancel the event by calling preventDefault
   event.preventDefault();
   // this will cause dispatchEvent to return false so the actual task doesn't get executed
}

A real life usecase for UI related events could be dispatching an event before closing a popup window:

function closeButtonHandler(event:Event):void{
   if(dispatchEvent(new MyWindowEvent(MyWindowEvent.CLOSE, true, true)){
      PopUpManager.closePopup(this);
   }
}

Cancelable events are also very interesting when you develop APIs because it offers powerful and easy to use hooks for the API user.
I am making heavy use of cancelable events in my swizdesktop lib. Catching the different update phase events you get hooks to stop the update process by calling preventDefault on the listened event.

Comments are closed.