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

后端 未结 3 870
死守一世寂寞
死守一世寂寞 2021-01-04 13:05

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

3条回答
  •  孤独总比滥情好
    2021-01-04 14:08

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

提交回复
热议问题