views:

61

answers:

2

I'm an actionscript developer getting into jquery/javascript development. I have a question regarding event handlers and binding/unbinding.

Say for instance that I have for an div with a img element with an onerror event handler in it. If i replace that that div with a new one do i need to remove the eventhandler bound to the img element. Since the img no longer will be in the document will browsers be smart enough to remove it or will I have a caused memory leak?

Comming from actionscript i usually try to constantly remove old eventhandlers. So do i need to do this when writing javascript for web browsers?

The event handlers are added with $('imgElement').error(errorFunction);

A: 

try using firequery, its a firefox plugin that shows all active event listeners and jquery.data()

I'm also curious as to whether it's best practice to unbind() events...

Haroldo
+4  A: 

If you're binding the events with jQuery just call .remove() on the old element before replacing it, or .empty() if you just want to clear it, both of these clean up event handlers for the element and it's children, or in the case of .empty(), just the children.

If you just replace it, e.g. .html(content) you will leak memory, as any handlers or data for those elements will be left on the $.cache object.

Nick Craver
i didn't know that .html(content) would leak memory! thanks!
Patricia
Are you sure? Looking at the jQuery source code, manipulation.js line 203:"// Remove element nodes and prevent memory leaks"
Phil
@phil- If you look at the code before it, you'll see there are several conditions in place that determine if that code executes :) SO Chat had the same memory leaking issue in the first preview, this was the cause.
Nick Craver