Custom event trick
Categories: actionscript
Written By: sebi
I learned some neat trick about custom events. We all need to use custom events in the applications. The usual way is to pass the custom property in the constructor of the event, like
public function DefaultCustomEvent(type:String, stringParameter:String, bubbles:Boolean=false, cancelable:Boolean=false) { super(type, bubbles, cancelable); this.stringParameter = stringParameter }
That’s ok, now imagine you used that event through your gigantic application, through thousands of lines. And whoops, you need to add a new parameter to your event, now a numberParameter.
public function DefaultCustomEvent(type:String, stringParameter:String, numberParameter:Number, bubbles:Boolean=false, cancelable:Boolean=false) { super(type, bubbles, cancelable); this.stringParameter = stringParameter this.numberParameter = numberParameter }
This isn’t a problem, until you used your custom event with the argument bubbles:Boolean=true in some places. How can you re-factor your code, to keep those bubbling events, but adding the new property to your event? If you can manage it, what’s if in a few day you’ll need to add an other property? I tell you. All you need to follow the pattern below.
package com.sebesteny.events { import flash.events.Event; public class CustomEvent extends Event { public static const CUSTOM_EVENT:String = "customEvent" public var stringParameter:String public var numberParameter:Number public function CustomEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false) { super(type, bubbles, cancelable); } public function withStringParameter( value:String ):CustomEvent { stringParameter = value return this } public function withNumberParameter( value:Number ):CustomEvent { numberParameter = value return this } } }
dispatchEvent( new CustomEvent( CustomEvent.CUSTOM_EVENT ).withStringParameter( "Hello World" ) ) dispatchEvent( new CustomEvent( CustomEvent.CUSTOM_EVENT ).withNumberParameter( 2009 ) ) dispatchEvent( new CustomEvent( CustomEvent.CUSTOM_EVENT ).withStringParameter( "Hello World" ).withNumberParameter( 2009 ) )
If you need to add a new property to your event, you can simply add the new method and property, you don’t need to touch your constructor, no need to write dummy nulls.