Use e.target to speed up your coding

November 24th, 2009

Here’s a quick tip that will make your Flash projects a bit easier – e.target. When you have more then one object on the stage that does the same thing, ie. is draggable or activates the same event when clicked, e.target will allow you to use a lot less code.

In this example, I’m creating two boxes on the stage, one red and one blue. I want to be able to drag both around the stage. Normally I would make a function for the red box and one for the blue box.

function dragRed(e:MouseEvent):void
{
redBlock.startDrag();
}

function dragBlue(e:MouseEvent):void
{
blueBLock.startDrag();
}

And, of course, the functions for stopDrag().

But now I do it this way. Here’s the entire code to make the boxes and make them draggable:

var redBlock:MovieClip = new MovieClip();
var blueBlock:MovieClip = new MovieClip();

redBlock.graphics.beginFill(0xFF0000,1);
redBlock.graphics.drawRect(50,50,100,100);
addChild(redBlock);

blueBlock.graphics.beginFill(0x0000FF,1);
blueBlock.graphics.drawRect(250,150,100,100);
addChild(blueBlock);

function moveBlock(e:MouseEvent):void
{
e.target.startDrag();
}

function stopBlock(e:MouseEvent):void
{
e.target.stopDrag();
}

redBlock.addEventListener(MouseEvent.MOUSE_DOWN, moveBlock);
redBlock.addEventListener(MouseEvent.MOUSE_UP, stopBlock);
blueBlock.addEventListener(MouseEvent.MOUSE_DOWN, moveBlock);
blueBlock.addEventListener(MouseEvent.MOUSE_UP, stopBlock);

When you MOUSE_DOWN on either the redBlock or the blueBlock, Actionscript will use e.target to make that one targeted by the function.

This will make targeting objects on the stage require a lot less coding.

Leave a Reply

Your email address will not be published. Required fields are marked *