Given the following elements:
<div class="container">
<span class="some-class">content</span>
..n span repetitions..
</div>
Given the following .on()
$('.some-class').on('click', function () { ... });
If you redraw the .container
with new span.some-class
, will you leak the old events?
What I mean is, before the redraw, should you do:
$('.some-class').off('click');
Thanks!
-
you should check out event delegation: api.jquery.com/delegateI.devries– I.devries2015年01月09日 17:01:04 +00:00Commented Jan 9, 2015 at 17:01
1 Answer 1
If you attach your event listener like this:
$(document).on({
click: function () {
// ...
}
}, '.some-class');
Then your event listener will not "leak" as you put it. You can redraw, add additional elements with .some-class
and they will all inherit the event listener. This has the added benefit of only registering one event listener instead of "x" listeners depending on how many .some-class
elements there are. Much better performance.
-
1It also adds the benefit of not having to perform a dom lookupPinoniq– Pinoniq2015年01月09日 12:27:29 +00:00Commented Jan 9, 2015 at 12:27