Flash: Invoking events based on changes using watch()…
In Flash 6 a neat method called watch() was introduced for registering event handlers - to be invoked when a specific property changes. To explain the use of the watch() method lets consider a Flash based car game where you want to alert the player if they are speeding;
// Create a the car object
var myCar:Object = new Object();
// Add a property that tracks the cars speed
myCar.speed = 0;
// Write the callback function to be executed if the speed property changes
var checkSpeed:Function = function(prop, oldVal, newVal, speedLimit) {
// Check whether speed is above the limit
if (newVal > speedLimit) {
trace ("You are speeding.");
}
else {
trace ("You are not speeding.");
}
// Return the value of newVal.
return newVal;
}
// Use watch() to register the event handler, passing as parameters:
// - the name of the property to watch: "speed"
// - a reference to the callback function speedWatcher
// - the speedLimit of 50 as the userData parameter
myCar.watch("speed", checkSpeed, 50);
// set the speed property to 44, then to 62
myCar.speed = 44; // output: You are not speeding
myCar.speed = 62; // output: You are speeding
// unwatch the object
myCar.unwatch("speed");
myObject.speed = 49; // there should be no output
(This example has been modified from the Actionscript Dictionary)
So essentially the watch() method calls the checkSpeed() function whenever the value of var speed changes, alerting the player if they are over the speed limit (var speedLimit). Easy no?.
Just remember the following in your callback function;
- If you are merely monitoring the property, return the
newValparameter. - If you are modifying the value of the property, return your own value.
- If you want to prevent changes to the property, return the
oldValparameter






Nice article, something that I wasn’t aware of.
This sort of thing would be good in forms for setting various event handlers to watch form elements values. Also a quick way of setting up a basic observer pattern, which might have better been done with a get/set..
Comment by Cameron Manderson — August 31, 2006 @ 12:50 pm
yeah its old AS 1.0 stuff. Good for simple scripts though. In the past I’ve used it for sequential animations
Comment by Richard Lee — August 31, 2006 @ 4:54 pm