Main Content
Different Events and Altering their Application
Hello and welcome. Here is how we left our circle last time:
package { import flash.display.*; import flash.events.*; public class graphical extends MovieClip { public var mc1:MovieClip = new MovieClip(); public function graphical() { mc1.graphics.lineStyle(1); mc1.graphics.beginFill(0xff0000); mc1.graphics.drawCircle(200,200,50); mc1.addEventListener("enterFrame",enterFrame_handler); this.addChild(mc1);mc1.graphics.endFill(); } private function enterFrame_handler(e:Event):void { mc1.alpha = mc1.alpha - 0.01; } } }
and here is how we will leave it this time (try clicking on the circle and then again a little bit later:
Today you will learn:
- The click event
- How to test whether an event handler exists
- How to remove an event handler
private function enterFrame_handler(e:Event):void { mc1.x += 3; }
In other words, the circle will move right every frame. Right? Wrong. That is what this function does, true, but as yet, because we removed the addEventListener function, it will not yet follow through on this: in the animation, it did not immediately move right. Handlers are useless without listeners.
Last but not least we have the click event, which contains all the new things for today:
private function click_handler(e:Event):void { if(mc1.hasEventListener("enterFrame")){
First line: we have our click event handler. Second line: if our move clip has an event listener for enterFrame then... Under these circumstance, the hasEventListener function means is our Movie Clip moving?but in general it does what is says on the tin. So, to recap, if our circle has that event listener, it is moving so:
mc1.removeEventListener("enterFrame",enterFrame_handler); } else{
stop. Basically. I suppose this counts as a new function, although it is the same as the addEventListener, but it removes the event listener, effectively stopping the movement. Of course, the next section is else (for when the circle is not moving):
mc1.addEventListener("enterFrame",enterFrame_handler); } } } }
Start the moving. And then we are done. Well done you! You made it! Save and compile: does it work? It should do. If it doesn't compare your code to the finished code that is at events.txt.
See you next time,
Harry.