views:

32

answers:

1

I have a few elements with a click event:

$$('.set_main').invoke('observe', 'click', set_main );

And i want to change the event observer. My question is, do I have to remove the event listeners first with something like:

$$('.thumb').each(function(item)
{
    Event.stopObserving(item, 'click', set_main);
});

or can i simply overwrite it with $$('.set_main').invoke('observe', 'click', view );?

This works anyway but i would like to know if this affects performance. Maybe im keeping event listeners on memory without any use.

A: 

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