AS3 - 检测变量并将值传递给侦听器

时间:2009-06-29 21:40:59

标签: flash actionscript-3

我从SO上的另一个问题得到以下代码,以跟踪计数器的变化值。

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));

        }

    }

}

我想要做的是在我更改它之前传递计数器的值以及向侦听器传递新值,以便我可以决定新值是否有效。

1 个答案:

答案 0 :(得分: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;
        }

    }

}
相关问题