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?
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.
If you execute that code twenty times, you'll end up with twenty event handlers bound; and yes, they will all fire.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With