• 4
  • January 22, 2009

Share!

Where is the watch object in AS3?

The watch object in AS2 was useful to monitor a variable’s change. But it was a problem regarding performances.

With AS3, the watch function disappeared, the object model of AS3 allows to do exactly the same. But not out of the box.

Adobe Livedoc suggests to use the Proxy pattern with setter and getter. Here is a class that does the same as the watch object and is easier to use than the proxy.

package
{
   import flash.events.Event;
   import flash.events.EventDispatcher;
   public class Model extends EventDispatcher
   {
       public static const VALUE_CHANGED:String = 'value_changed';
       private var _number:Number = Number;
       public function Model():void
       {
           trace('The model was instantiated.');
       }
       public function set number(newNb:Number):void
       {
          _number=newNb;
          this.dispatchEvent(new Event(Model.VALUE_CHANGED));
       }
       public function get number():Number
      {
          return _number;
 
      }
   }
}

The _number variable can be replaced by whatever type is needed.

Usage:

var objectToWatch:Model = new Model();
objectToWatch.addEventListener(Model.VALUE_CHANGED, onValuedChanged);
 
function onValuedChanged(e:Event) {
   //do what you need here
}

4 Comments Post a comment

  1. August 7, 2009 at 2:35 pm / Reply

    I don’t under stand what you have done here completely
    more or less
    lets say I have a

    var cc:int;

    I want to watch cc

    how can this be done with the code you entered above?

    when a certain function is called cc++;

    thanks

  2. February 1, 2010 at 11:04 am / Reply

    Is your second dispatched event really useful (the one in the getter) ?
    Anyway, it will never be dispatched AFTER the ‘return’ keyword.

    • February 1, 2010 at 11:09 am / Reply

      Ah ah! thanks! Since this code is online, none saw this! You’re right the second dispatch is useless..not to mention completely useless if after the return..

      Thanks!

  3. Pingback: Detectar dirección con ActionScrip 2 :digilabs.com.ar

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">