是否可以使用EventListener来监听变量并检测该变量的值何时发生变化?谢谢.
如果将它全部包装到类中,这很容易做到.我们将使用getter/setter方法.每当调用setter方法时,setter方法都将调度和调度.
(注意:Setter和Getters被视为属性).您只需分配一个值,而不是调用方法(例如someVar = 5
,someVar(5);
即使setter/getter是函数/方法,它们也被视为属性.
//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)); } } }