Creating clickable movie clips in ActionScript 3.0

One of the biggest improvements in the ActionScript 3.0 language is the new event model. In previous versions of ActionScript, the event model may have differed slightly (or not so slightly) depending on which symbols you were using. A MovieClip’s event model may have been different from a component or other class/symbol, but now, everything uses the EventDispatcher and addEventListener() method. For an example of the old versus new methods, look at the following example:

// AS2
this.createEmptyMovieClip("mc", this.getNextHighestDepth());
mc.beginFill(0xFF0000);
mc.moveTo(0, 0);
mc.lineTo(100, 0);
mc.lineTo(100, 80);
mc.lineTo(0, 80);
mc.lineTo(0, 0);
mc.endFill();
mc._x = 80;
mc._y = 60;
mc.onRelease = clickHandler;

function clickHandler():Void {
trace("You sunk my battleship!");
}

NOTE: This code often uses an anonymous method, such as: mc.onRelease = function():Void {...}.

In ActionScript 3.0, the same code could be rewritten as follows:

// AS3
var mc:MovieClip = new MovieClip();
mc.graphics.beginFill(0xFF0000);
mc.graphics.drawRect(0, 0, 100, 80);
mc.graphics.endFill();
mc.x = 80;
mc.y = 60;
mc.addEventListener(MouseEvent.CLICK, clickHandler);
addChild(mc);

function clickHandler(event:MouseEvent):void {
trace("You sunk my battleship!");
}

If you test the following code, you’ll notice that the shape on the Stage is clickable, although the mouse cursor doesn’t show the hand icon. If you want the hand cursor to appear when your mouse is over the movie clip, add the following line of code before the call to the addEventListener() method:

mc.buttonMode = true;