2010年12月30日木曜日

クロージャでaddEventListenerしたEventをremoveするメモ

クロージャでaddEventListenerしたEventをremoveするメモ

1arguments.callee

を使う。

Docs[argument]
arguments オブジェクトは、関数の引数の保存や、引数へのアクセスに使用されます。関数の本体に含まれる場合、arguments オブジェクトにはローカルの arguments 変数を使用してアクセスできます。


1var count:Number = 0
2addEventListener(Event.ENTER_FRAME, function():void {
3    count++
4    if(count > 10){
5            removeEventListener(Event.ENTER_FRAME,arguments.callee);
6     }
7}



以下、使ってみたsample

クロージャの中でイベントを削除する - wonderfl build flash online



01package {
02    import flash.geom.Point;
03    import flash.events.Event;
04    import flash.display.Shape;
05    import flash.events.MouseEvent;
06    import flash.display.Sprite;
07     
08    [SWF(width = "465", height = "465", frameRate = "60", backgroundColor = "000000")]
09 
10    public class Line extends Sprite {
11        public function Line() {
12            // write as3 code here..
13            init();
14        }
15         
16        private function init():void
17        {
18         stage.addEventListener(MouseEvent.MOUSE_DOWN,mouseDownHandler);
19        }
20 
21        private function mouseDownHandler(e:MouseEvent):void
22        {
23         stage.addEventListener(MouseEvent.MOUSE_MOVE,mouseMoveHandler);
24         stage.addEventListener(MouseEvent.MOUSE_UP,mouseUpHandler);  
25        }
26         
27        private function mouseUpHandler(e:MouseEvent):void
28        {
29            stage.removeEventListener(MouseEvent.MOUSE_MOVE,mouseMoveHandler);
30            stage.removeEventListener(MouseEvent.MOUSE_UP,mouseUpHandler);
31        }
32 
33        private function mouseMoveHandler(e:MouseEvent):void
34        {
35            drawLines(mouseX,mouseY);
36        }
37         
38        private function drawLines(startX:Number,startY:Number):void
39        {
40            var line:Shape = new Shape();
41            var col:uint = Math.random() * 0xFFFFFF;
42            var count:Number = 0;
43            addChild(line);
44            line.x = startX;
45            line.y = startY;
46            line.graphics.lineStyle(1,col);
47            line.graphics.moveTo(20,0);
48            line.addEventListener(Event.ENTER_FRAME,
49                                function():void{
50                                    count+= 0.1;
51                                    var px:Number = 20 * (Math.cos(count) + count * Math.sin(count));
52                                    var py:Number = 20 * (Math.sin(count) - count * Math.cos(count));
53                                    line.graphics.lineTo(px,py);
54                                    line.alpha -= 0.005;
55                                    if(count > 10){
56                                        removeChild(line);
57                                        line.removeEventListener(Event.ENTER_FRAME,arguments.callee);
58                                    }
59             
60            });
61        }
62    }
63}

0 件のコメント:

コメントを投稿