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.