Alex Rivera | Logout

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

Asked 2008-11-20T21:24:13.037
10

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

Edit
Report

1 Answer

2

@BrianHodge: How do you actually use your example? How do you call the set function? How do you refer to it? Where do pass the variable to be changed..?

Let's say if I want to change the wrapped variable with a button click, for example. I have to confess that I tried some other codes and example (getter/setter) type, with dispatchEvent or without,and I can't get over it! But your example seems to be exactly what I need, just can't make it work.

I get the The model was instantiated when I set the function as document class. That's all.

I found out, at last, for people like me who are loosing time with this dispatch thing!
In my case the _someVar variable has to be data typed as a String (same thing for fornewVal).

OnceTestDocClass is set as your document class; you refer to the Model instantiated like this:

_model.someVariable="new stuff";  

I was trying to change the value like this:

_model.someVariable("new stuff");  

You can add some trace actions in the Model class to have a clear demo in the output panel:

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:String = "default";

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

    public function set someVariable(newVal:String):void
    {
      trace ("before " + _someVar);
      _someVar = newVal;
      trace ("after " + _someVar);
      this.dispatchEvent(new Event(Model.VALUE_CHANGED));
    }
  }
}

It's not much, but these things can cost some people a whole lot of time =)

answered 2009-04-24T23:34:00.193

Your Answer