2009-06-29 51 views
0

我從SO上的另一個問題得到以下代碼來跟蹤計數器的變化值。AS3 - 檢測變量變化並將值傳遞給監聽者

package com.my.functions 
{ 
    import flash.events.Event; 
    import flash.events.EventDispatcher; 

    public class counterWithListener extends EventDispatcher 
    { 

     public static const VALUE_CHANGED:String = 'counter_changed'; 
     private var _counter:Number = 0; 

     public function counterWithListener() { } 

     public function set counter(value:Number):void 
     { 
      _counter = value; 
      this.dispatchEvent(new Event(counterWithListener.VALUE_CHANGED)); 

     } 

    } 

} 

我想要做的就是通過計數器的值之前,我改變了它,以及新價值的聽衆,所以我可以在新的值是否有效決定。

回答

2

您將要創建一個自定義事件:

package 
{ 
    import flash.events.Event; 

    public class CounterEvent extends Event 
    { 
     public static const VALUE_CHANGED:String = 'valueChanged'; 

     public var before:int; 
     public var after:int; 

     public function CounterEvent(type:String, before:int, after:int) 
     { 
       this.after = after; 
       this.before = before; 

       //bubbles and cancellable set to false by default 
       //this is just my preference 
       super(type, false, false); 
     } 

     override public function clone() : Event 
     { 
       return new CounterEvent(this.type, this.before, this.after); 
     } 
    } 
} 

這會將上面的代碼更改爲:

package com.my.functions 
{ 
    import CounterEvent; 
    import flash.events.EventDispatcher; 

    public class counterWithListener extends EventDispatcher 
    { 
     private var _counter:Number = 0; 

     public function counterWithListener() { } 

     public function set counter(value:Number):void 
     { 
       this.dispatchEvent(new CounterEvent(CounterEvent.VALUE_CHANGED, _counter, value)); 
       _counter = value; 
     } 

    } 

} 
+0

感謝 - 看起來不錯。將現在進行測試。 – Josh 2009-06-29 21:55:49