Flash AS3-检测变量变化并将值传递给侦听器
我从另一个问题中得到了以下代码,以便跟踪计数器的变化值Flash AS3-检测变量变化并将值传递给侦听器,flash,actionscript-3,Flash,Actionscript 3,我从另一个问题中得到了以下代码,以便跟踪计数器的变化值 package com.my.functions { import flash.events.Event; import flash.events.EventDispatcher; public class counterWithListener extends EventDispatcher { public static const VALUE_CHANGED:String = 'c
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));
}
}
}
我要做的是在我更改计数器之前将计数器的值以及新值传递给侦听器,以便我可以确定新值是否有效。您需要创建一个自定义事件:
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;
}
}
}