Widget watch()

Dojo 1.6 introduces a new watch() method on all widgets as a consistent way to monitor and respond to changes in widget properties. The dojo.Stateful class is now the super class of all widgets, and therefore widgets implement the standard get/set/watch method pattern used by all Stateful objects. This makes it easy to setup generic code that can bind to properties of any Stateful object, including widgets with real-time response to changes. In Dojo 1.5, widget's were partially converted to the Stateful interface with the introduction of get/set methods, but in 1.6, this conversion was completed.

First, let's review the watch() API. The watch() method is based on Mozilla JavaScript's watch method. The first argument is the name of the property to monitor, and the second argument is the handler function to be called when the property changes. The handler function is called with |this| set to the target widget, the first argument is the property name, the second argument is the old value, and the third argument is the new value. The widget watch() method also allows first argument to be optional. You can omit the property name argument to monitor all property changes.

Now, let's look at how we might use this new method. We could use watch() to monitor changes in a form element:

// create a Textbox
var textBox = new dijit.form.TextBox({..}, inputNode);
// get a node to display the value
var target = dojo.byId("target");
// show the initial value
updateDisplay();
// watch for changes, and update the display when the value changes
textBox.watch("value", updateDisplay);

function updateDisplay(){
  // get the current value from the textbox and set it in the node
  target.innerHTML = textBox.get("value");
}

We could monitor any other property of widgets with watch() and affect any other part of our page, including other widget properties.

In Dojo 1.7, we are looking forward to some powerful new binding components that automatically bind Stateful objects to other widgets and elements for direct updates.