Josh
Josh

Reputation: 6322

AS3 - Detecting variable change and pass values through to listener

I've got the following code from another question on SO to track the changing value of a counter.

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

        }

    }

}

What I would like to do is pass the value of the counter before I changed it as well as the new value to the listener so I can decide on whether the new value is valid.

Upvotes: 0

Views: 3879

Answers (1)

Joel Hooks
Joel Hooks

Reputation: 6565

You will want to create a custom event:

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

This will change your above code to:

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

    }

}

Upvotes: 2

Related Questions