March 16, 2009
Are your event handlers bad?
Event handlers can be bad. They're not intrinsically bad - that's how shit gets done in AS3. It's the way they often get written that can be bad. Consider the following example:
-
package
-
{
-
import fl.motion.Color;
-
-
import flash.display.DisplayObject;
-
import flash.display.Sprite;
-
import flash.events.Event;
-
import flash.events.MouseEvent;
-
-
public class Nothing extends Sprite
-
{
-
private var square:Sprite;
-
-
public function Nothing()
-
{
-
square = new Sprite();
-
square.graphics.beginFill( 0xFFFFFF, 1 );
-
square.graphics.drawRect( 0, 0 , 50, 50 );
-
square.graphics.endFill();
-
square.addEventListener( MouseEvent.CLICK, click );
-
addChild( square );
-
}
-
-
private function click( event:MouseEvent ):void
-
{
-
var clickedObject:DisplayObject = event.target as DisplayObject;
-
var tint:uint = 0xFF0000;
-
var color:Color = new Color();
-
-
color.setTint( tint, 1 );
-
clickedObject.transform.colorTransform = color;
-
}
-
-
}
-
}
Great. So a sprite is tinted red when its clicked. But what happens when you have to tint that sprite at other times, like when the application loads? All the code that does the tinting is locked up inside the event handler - the problem there is that the event handler needs a MouseEvent to run.
A better, more reusable, and more modular approach would be:
-
public function tint( obj:DisplayObject ):void
-
{
-
var tint:uint = 0xFF0000; //or better, make this an argument
-
var color:Color = new Color();
-
-
color.setTint( tint, 1 );
-
obj.transform.colorTransform = color;
-
}
-
-
private function click( event:MouseEvent ):void
-
{
-
var clickedObject:DisplayObject = event.target as DisplayObject;
-
tint( clickedObject );
-
}
You see? The event handler just notifies us that something needs to be tinted. The actual tinting happens elsewhere. Now, code that does work does not need anything other than a reference to a DisplayObject to run! Now, you can tint an object when the application loads. You can tint an object on a timer. Now, you can tint anything, at anytime! Now its testable and reusable! And, it's a very easy concept to master.
Get what you need from an event object, and get out.
When you write event handlers, think about what they are actually doing. What do you actually need from the event object? How would you test the event handler? Or better yet, how would you make the same thing that happens in the event handler, happen without the event?
Comments
Leave a replyNo comments