views:

209

answers:

3

I have application that brings response via Ajax and creates 5-20 new jQuery click listeners on each refresh. Both IE and mozilla browsers seem to be slowing down with usage. Can this slow down browser performance significantly. Can listeners be "released"?

+2  A: 

Listeners set using .bind() are released when the element is removed or .unbind()ed. Those set using .live() persist until you call .die() or the element they are bound to is removed (which may be somewhere in the DOM if you specify, otherwise it'll default to the DOM root - .live() works by not binding to the target element so the element can be removed/replaced/updated and the event listeners are still bound).

5-20 listeners sounds a few too many - consider binding less handlers if possible as older browsers will crack under the pressure far quicker than newer ones.

Andy
make sure the elements are removed via jQuery. the empty() and html() method will work.
David Murdoch
+2  A: 

You can unbind a listener using unbind:

$("a").unbind("click"); // remove click event handler(s)
$("a").unbind(); // remove all event handlers

and remove live events using die:

$("#foo").die(); // remove all live events
$("a").die("click"); // remove live click event handlers
karim79
+2  A: 

To add to what Andy said about live.

You should probably be using delegate or live on the elements you are adding to the page. It sounds like you are not binding unique events to the new elements (on each refresh) but rather reusing functions.

In jQuery 1.4.2 use can use delegate() like this:

// the container,        the selector, "the event", the function to be called
$("#container").delegate(".selector",  "click",     function(){
  // do stuff...
});

This would only need to be called once and every new element with the "selector" class added to the "#container" will have their click event bound

David Murdoch