stopObserving

Event.stopObserving(element, eventName, handler[, useCapture = false])

Unregisters an event handler.

This function is called with exactly the same argument semantics as observe. It unregisters an event handler, so the handler is not called anymore for this element+event pair.

Why won't it stop observing!?

For stopObserving to work, you must pass exactly the same arguments as those you did to the corresponding observe call. Complying with this seems straightforward enough, but there is a common pattern where code is not what it seems to be:


var obj = {
  …
  fx: function(event) {
    …
  }
};

Event.observe(elt, 'click', obj.fx.bindAsEventListener(obj));
…

// THIS IS WRONG, DON'T DO IT!
Event.stopObserving(elt, 'click', obj.fx.bindAsEventListener(obj)); // Won't work!

Here, although it may seem fine at first glance, you must remember that bindAsEventListener returns a fresh anonymous function that wraps your method. This means that every call to it returns a new function. Therefore, the code above requests stopping on another function than was used when setting up observation. No match is found, and the original observer is left untroubled.

To avoid this, you need to "cache" the bound functions (which is, for instance, what script.aculo.us does in many of its classes), like th is:


var obj = {
  …
  fx: function(event) {
    …
  },
};

obj.bfx = obj.fx.bindAsEventListener(obj);

Event.observe(elt, 'click', obj.bfx);
…
Event.stopObserving(elt, 'click', obj.bfx);

See also

The unloadCache function is related and worth a look.