Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free.

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!

share|improve this question
    
you should check out event delegation: api.jquery.com/delegate –  I.devries Jan 9 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.

share|improve this answer
1  
It also adds the benefit of not having to perform a dom lookup –  Pinoniq Jan 9 at 12:27

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.