Coverage of jQuery binding events

Time:2020-2-18

In ECMAScript, the binding of events is overlay, not overlay as many people think. Such as:

$('button').click(function(){
    alert("first");
});
$('button').click(function(){
    alert("second");
});

After clicking the button, the first pop-up box will pop up first, and then the second pop-up box will pop up (instead of just the second pop-up box).

In many cases, we want to rebind events for elements after executing a function and making some judgments, instead of keeping multiple event listeners at the same time. (for example, before entering the password, click “login” to prompt “enter password”; after the password is verified successfully, click “login” to prompt “login succeeded”)

Here are two ways to achieve binding event coverage:
(I’m going to show my idiom level, high energy ahead, and non combatant evacuation)

1. Bring the dead back to life

$('button').die().live('click',function(){
//New binding event
});

First usedie()Method to remove all passeslive()Method to add an event handler to the elementlive()Method to bind a new event.
The premise of this method is that the covered method must also passlive()Method, otherwisedie()Method “kill not dead” them, will have no effect at all.

2. Hard to get

$("button").unbind('click').click(function(){
//New binding event
});

Similar to the first method, useunbind()Method to remove the event handler of all elements, and then bind the new event (later it can be changed tobind()Method).
This method also has a premise, that is, if the covered method is passedlive()Method binding, there will be no effect.

I’m sure there must be a little friend who needs to ask when to use itbind()Method orlive()Method? What is the difference between the two?
However, I’m going to leave work. This problem is a little complicated. I’ll leave it for the next article to explore with you.