Tuesday, May 02, 2006

Object.watch, santa's little helper

This handy little function allows you to watch when a certian property of any object changes and call a callback. There are a few catches however.

  • The callback has to have access to the watched object (in the same scope).

  • Only one callback can occur per property of an object (no multiple watches).

  • The callback function is always called with three arguments: property, oldval, newval.

  • The callback function must return the argument containing the new value of the property watched in order for that property to be set.

Using Object.watch is really easy dispite of its own catches. All you have to do is setup a variable to watch.

var watchee:Object = {toWatch:"Test"};

Once that is done you need to setup a callback function.

function watchTrigger(property, oldval, newval){
trace("newValue: "+newval);

return newval;

You absolutely must return newval at the end of your callback. If you don't do this the property won't be set. Now to actually setup the watch.

watchee.watch( "toWatch", watchTrigger);

Finally you have to actually change the value of the watched property to invoke the callback.

watchee.toWatch = "New Test";
trace("Actual Data: "+watchee.toWatch); //just to make sure

When you compile that code the trace output window should display the new value of the property in both traces.

Is there any way to avoid these limitations when using Object.watch?
Not currently, but I'm trying to get a WatchManager class working that will allow remove three (possible four) of the limitations: the three arguments property, oldval, and newval, won't be needed; more than one callback per property; the callback won't have to return newval.

I hope to have this class done within a week or so. I'll be sure to post it here when it's completed in its entirety.


Post a Comment

<< Home