class Abstract.TimedObserver
Description
An abstract DOM element observer class, subclasses of which can be used to periodically check a value and trigger a callback when the value has changed.
A TimedObserver
object will try to check a value using the getValue()
instance method which must be defined by the subclass. There are two
out-of-the-box subclasses:
Form.Observer
, which serializes a form and triggers when the result has
changed; and Form.Element.Observer
, which triggers when the value of a
given form field changes.
Using TimedObserver
implementations is straightforward; simply instantiate
them with appropriate arguments. For example:
new Form.Element.Observer( 'myelement', 0.2, // 200 milliseconds function(el, value){ alert('The form control has changed value to: ' + value) } )
Now that we have instantiated an object, it will check the value of the form control every 0.2 seconds and alert us of any change. While it is useless to alert the user of his own input (like in the example), we could be doing something useful like updating a certain part of the UI or informing the application on server of stuff happening (over Ajax).
The callback function is always called with 2 arguments: the element given when the observer instance was made and the actual value that has changed and caused the callback to be triggered in the first place.
Creating Your Own TimedObserver Implementations
It's easy to create your own TimedObserver
implementations: Simply subclass
TimedObserver
and provide the getValue()
method. For example, this is the
complete source code for Form.Element.Observer
:
Form.Element.Observer = Class.create(Abstract.TimedObserver, { getValue: function() { return Form.Element.getValue(this.element); } });