Event Listeners
Each property of your POJOs has listener support. That is, for a
property
foo there's a method
addFooListener(js.mvc.Listener) and
removeFooListener(js.mvc.Listener). You can use these
methods in your JavaScript to perform business logic, validations,
etc. The event listeners form the foundation of the HTML Bindings
code.
js.mvc.Listener
The
js.mvc.Listener
class is useful for quickly creating a listener that can be called
by:
- A POJO when a property is changed
- The remote proxy when a method completes
Creating a listener is easy, and can be done in a number of ways:
Creating a listener with a function
function handleFooChanged() {
alert("Hey! Who changed foo?");
}
var fooChangedListener = new js.mvc.Listener(handleFooChanged);
var bar = new com.foo.Bar();
bar.addFooChangedListener(fooChangedListener);
In the above example, we simply declare a function
handleFooChanged() which is called when the
foo
attribute is changed. If any state information is required (like
which Bar object we're listening to), that state can be added to
the listener instance through something like
fooChangedListener.bar = bar.
Creating a listener with a closure
var bar = new com.foo.Bar();
bar.addFooChangedListener(new js.mvc.Listener(function() {
alert("The foo property has changed: " + bar.getFoo());
}));
In this example, our listener can access the
bar
variable because JavaScript sets up a
closure in our
anonymous function declaration. Closures are somewhat similar to
anonymous inner classes, especially in that they can be the cause
of memory leaks if you're not careful how you use them. However,
most of the time closures are a wonderful thing.