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);
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$.cacheobject.