AS3 Snippet #2: Watch for changing properties
Today I stumbled across a handy utility class called ChangeWatcher, which lives inside the mx.binding.utils package. It provides you with a handy way of watching other object’s properties.
Here’s how it’s used:
ChangeWatcher.watch(object, “property”, handler);
Object – the object which owns the property
“property” – the property you want to watch
handler – the function name of the handler
Whenever the property of the object changes, the handler will respond. Quite handy, right?
edit:
Here’s an example for you:
Let’s say we have a class called WatchMe. Inside that class we have a public variable called ImBeingWatched. We’d like to trigger a function whenever this variable changes. To do this, we simply add one line of code:
package { import mx.binding.utils.*; import flash.display.*; import flash.events.*; public class WatchMe extends MovieClip { [Bindable] public var ImBeingWatched:Boolean = true; public function WatchMe():void { ChangeWatcher.watch(this, "ImBeingWatched", doSomething); } private function doSomething(e:Event):void { // do something ... } } }
As you can see, this works pretty much like using [Bindable] variables. But, in some cases this method proves quite handy.
Update: Oops! Typo. The property that ChangeWatcher is watching must be [Bindable] and Public for it to work.
January 5th, 2009 at 11:54
Can u please post a working example of ChangeWatcher
January 13th, 2009 at 02:20
your final update (property must be bindable) saved my day
Thanks for posting.
June 10th, 2010 at 18:48
i could not make this work in flash actionscript 3.
suprisingly,
ChangeWatcher.canWatch(this, “ImBeingWatched”); returns ‘false’ all the time.
is this ‘ChangeWacther’ to be used only in the flex?
June 14th, 2010 at 15:35
Yes, the ChangeWatcher is a Flex only util.