AS3 - 我可以检测到使用addEventListener一个变量的值的变化? [英] AS3 - Can I detect change of value of a variable using addEventListener?

查看:308
本文介绍了AS3 - 我可以检测到使用addEventListener一个变量的值的变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用事件监听来听一个变量并检测该变量的变化,当值?谢谢你。

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

推荐答案

这是很容易的,如果你把它包装成所有一类的事情。我们将使用getter / setter方法​​。 setter方法​​将调度和事件时,它被调用。

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.

(注:getter和setter方法​​被视为属性)你只是分配一个值,而不是调用一个方法(如someVar = 5,而不是someVar(5);即使制定者/吸气的函数/方法,它们是像对待属性。

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

有关最好的教程检查出李某Brimlow的 www.gotoandlearn.com 和的 theflashblog.com

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

我的作品在 www.hodgedev.com

这篇关于AS3 - 我可以检测到使用addEventListener一个变量的值的变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆