Two jQuery.on events connected two times?

Say we have a lot to do. We use $('body').on('click', '.todo', do_stuff) instead of $('.todo').click(do_stuff) , so we will only attach one event listener to the DOM.

However, I use a little MVC. For each view, this code is $('body').on('click', '.todo', do_stuff) . So if we have 20 to showers, does this body have 20 with listeners connected, or only one? will they all shoot?

+6
source share
3 answers

You must kill the previous event handler:

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

Including the function of the event handler in the off() function, only this handler will be deleted, and not all the others that are called by the same elements / events. Also, avoid anonymous functions while doing this.

Currently, it is also proposed to abandon unbind() and kill() . on() / off() should meet all your event processing needs, including future real-time bindings and pending results.

+5
source

If you run this code twenty times, you end up with twenty event handlers; and yes, they will all shoot.

+4
source

This means that body has 1 listener, which checks for all click events and checks the DOM structure of the target to see if it contains a .todo element.

There will only be 1 listener in the body, no matter how many .todo elements you have.

Example (draft 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> 
+2
source

Source: https://habr.com/ru/post/912309/


All Articles