Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are two equal jQuery .on events binded twice?

Let's say we have a lot of to dos. We use $('body').on('click', '.todo', do_stuff) instead of $('.todo').click(do_stuff) so we'll only attach one event listener to the DOM.

However, I'm using a small MVC. Every to do view has this code $('body').on('click', '.todo', do_stuff). So if we have 20 to dos, does that mean body has 20 on listeners attached or just one? will they all fire?

like image 446
CamelCamelCamel Avatar asked Apr 03 '12 10:04

CamelCamelCamel


3 Answers

You should kill the previous event handler:

<script>
    $('body').off('click','.todo', do_stuff);
    $('body').on('click', '.todo', do_stuff);
</script>

Including the actual event handler function in the off() function, will only remove that specific handler, and not all others triggered by the same elements/events. Also, avoid anonymous functions while doing this.

It's also currently suggested to abandon unbind() and kill(). on() / off() should suit all your event handling needs, including future live binding and deferred outcomes.

like image 66
keystorm Avatar answered Oct 12 '22 22:10

keystorm


If you execute that code twenty times, you'll end up with twenty event handlers bound; and yes, they will all fire.

like image 42
Anthony Grist Avatar answered Oct 12 '22 23:10

Anthony Grist


It means that body has 1 listener which inspects all click events and checks the DOM structure of the event target to see if it contained a .todo element.

There will only ever be 1 listener on the body, regardless of how many .todo elements you have.

Example (rough code, ignore ready handler etc.):

<script>
    $('body').on('click', '.todo', myFunc); 
    // results in 1 handler on the Body, which will be called when each .todo element is clicked
</script>

<body>
    <div class="todo">Foo</div>
    <div class="todo">Bar</div>
    <div class="todo">Baz</div>
</body>
like image 37
Rory McCrossan Avatar answered Oct 13 '22 00:10

Rory McCrossan