AS3 - Can I detect change of value of a variable using addEventListener?

shibbydoo picture shibbydoo · Nov 20, 2008 · Viewed 29.5k times · Source

Is it possible to use EventListener to Listen to a variable and detect when the value of that variable changes? Thanks.

Answer

Brian Hodge picture Brian Hodge · Nov 25, 2008

This is quite easy to do if you wrap it all into a class. We will be using getter/setter methods. The setter method will dispatch and event whenever it is called.

(Note: Setters and Getters are treated like properties). You merely assign a value, as opposed to calling a method (e.g someVar = 5 instead of someVar(5); Even though setters / getters are functions/methods, they are treated like properties.

//The document class
package
{
  import flash.display.Sprite;
  import flash.events.Event;
  import flash.events.EventDispatcher;

  public Class TestDocClass extends Sprite
  {
    private var _model:Model;

    public function TestDocClass():void
    {
      _model = new Model();
      _model.addEventListener(Model.VALUE_CHANGED, onModelChanged);
    }

    private function onModelChanged(e:Event):void
    {
      trace('The value changed');
    }
  }
}

//The model that holds the data (variables, etc) and dispatches events. Save in same folder as DOC Class;
package
{
  import flash.events.Event;
  import flash.events.EventDispatcher;

  public class Model extends EventDispatcher
  {
    public static const VALUE_CHANGED:String = 'value_changed';
    private var _someVar:someVarType;

    public function Model():void
    {
      trace('The model was instantiated.');
    }

    public function set someVariable(newVal:someVarType):void
    {
      _someVar = newVal;
      this.dispatchEvent(new Event(Model.VALUE_CHANGED));
    }
  }
}