class method Event.stopObserving
Event.stopObserving(element[, eventName[, handler]]) → Element
-
element
(Element
|String
) – The element to stop observing, or its ID. -
eventName
(String
) – (Optional) The name of the event to stop observing, in all lower case, without the "on" — e.g., "click" (not "onclick"). -
handler
(Function
) – (Optional) The handler to remove; must be the exact same reference that was passed toEvent.observe
.
Unregisters one or more event handlers.
If handler
is omitted, unregisters all event handlers on element
for that eventName
. If eventName
is also omitted, unregisters all
event handlers on element
. (In each case, only affects handlers
registered via Prototype.)
Examples
Assuming:
$('foo').observe('click', myHandler);
...we can stop observing using that handler like so:
$('foo').stopObserving('click', myHandler);
If we want to remove all 'click' handlers from 'foo', we leave off the handler argument:
$('foo').stopObserving('click');
If we want to remove all handlers for all events from 'foo' (perhaps we're about to remove it from the DOM), we simply omit both the handler and the event name:
$('foo').stopObserving();
A Common Error
When using instance methods as observers, it's common to use
Function#bind
on them, e.g.:
$('foo').observe('click', this.handlerMethod.bind(this));
If you do that, this will not work to unregister the handler:
$('foo').stopObserving('click', this.handlerMethod.bind(this)); // <== WRONG
Function#bind
returns a new function every time it's called, and so
if you don't retain the reference you used when observing, you can't
unhook that function specifically. (You can still unhook all handlers
for an event, or all handlers on the element entirely.)
To do this, you need to keep a reference to the bound function:
this.boundHandlerMethod = this.handlerMethod.bind(this);
$('foo').observe('click', this.boundHandlerMethod);
...and then to remove:
$('foo').stopObserving('click', this.boundHandlerMethod); // <== Right