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

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

Answers


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

For the best tutorials check out Lee Brimlow's www.gotoandlearn.com and theflashblog.com

My works are at www.hodgedev.com


Need Your Help

Understanding Gen.unit(x)

scala monads

Working through Functional Programming in Scala, the book shows the Gen Monad definition. Gen, as I understand, is a ScalaCheck trait.

Enable debug logs for Endeca forge and dgidx

endeca endeca-workbench

Could anybody please guide me on how to enable debug log for forge and dgidx on endeca?