Attaching a Handler to Many Events - J Query

In many common situations, one needs to bind the same handler function to more than one event (on the same element, that is). You could always do something like this:

That is not such a problem if the function is short, but for longer blocks of code, repeating them over and over won’t be that trivial and is definitely not the best approach.


There’s more than a single solution to this simple but recurrent problem.One way to solve it without repeating yourself too much would be as follows:

Defining a function once and then referring to it multiple times is not a bad approach,but there’s an even simpler one provided by jQuery.
bind() accepts a list of events separated by spaces. That means you can solve the previous problem like this:

You can also apply this behavior to unbind() and one().To unbind a certain function, you need to have a reference to it, so even if you are using the multi event feature, you still need to keep a reference to the handler. If you don’t pass the function to unbind(), then any other event handler bound to that event will be removed as well:

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

J Query Topics