Tip - Extending TimedObserver

Prototype.js provides very useful object TimedObserver which periodically queries some value and executes callback when the value has changed. Prototype ships with two specialised TimedObservers - Form.Element.Observer and Form.Observer. Those allows for observing changes of values in form elements or whole forms.

But what if you need to detect other changes? A simple way to achieve that is to create a class extending Timed.Observer.

For example, if you want to observe changes in style of element, you could simply create a StyleObserver:

StyleObserver = Class.create(Abstract.TimedObserver, {
  observedStyle: '', //the name of observed style property
   * overriding initialisation method, cause we need to set the name of style property we want to observe
  initialize: function($super, element, frequency, callback, observedStyle) {
    $super(element, frequency, callback); //we need to call initialize method of parent class. See [1]
    this.observedStyle= observedStyle;    
    * this is the key funtion. TimedObserver will call it with {{frequency}}
    * try to keep this method short and fast, cause it will be called many times
  getValue: function() {
     return Element.getStyle(this.element, this.observedStyle);

Now, if you want to observe changes in visibility of an element, you can instantiate this observer:

new StyleObserver(
    1, //1 second period
    function(el,value){   //the callback  
        alert('new display: ' + value)
    'display'   //the style you want to observe

It is possible to create similar observers to match your needs. The key is to provide getValue method, which is used by Abstract.TimedObserver to gather observed data. You can skip initialise method if you do not need to pass anything other than element, period and callback to the observer.


[1] Class.create documentations explains how $super works.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License