How to add and delete a listener in Javascript
In js, event listening is to bind an event using addEventListener, which is very common and simple in jquery, but complicated in native js, here we have sorted out the tests and examples of various methods for the addEventListener event for your reference.
When I added a listener when I was playing the player two days ago, I encountered some trouble in deleting the listener. After I checked it, I found that the parameters must be exactly the same. What is exactly the same? In other words:
The Code is as follows:
$ ('. Video') [0]. addEventListener ('timeupdate', currentTimeHandler, true );
For example, you need to input three parameters to delete the statement. Why do you need to delete the statement? Yes, it's right here:
When adding and removing, the third parameter can indeed be left blank, but their default conditions are different !!
Generally, addEventListener is false...
1. Add Custom Event listening
The Code is as follows:
Var eventHandlesCounter = 1; // counts the number of added event listeners. 0 is reserved.
Function addEvent (obj, evt, fn ){
If (! Fn. _ EventID) {fn. _ EventID = eventHandlesCounter ++ ;}
If (! Obj. _ EventHandles) {obj. _ EventHandles = [];}
If (! Obj. _ EventHandles [evt]) {
Obj. _ EventHandles [evt] = [];
If (obj ["on" + evt] instanceof Function ){
Obj. _ EventHandles [evt] [0] = obj ["on" + evt];
Obj ["on" + evt] = handleEvents;
}
}
Obj. _ EventHandles [evt] [fn. _ EventID] = fn;
Function handleEvents (){
Var fns = obj. _ EventHandles [evt];
For (var I = 0; I <fns. length; I ++)
Fns [I]. call (this );
}
}
2. Custom deletion event listening
The Code is as follows:
Function delEvent (obj, evt, fn ){
If (! Obj. _ EventHandles |! Obj. _ EventHandles [evt] |! Fn. _ EventID ){
Return false;
}
If (obj. _ EventHandles [evt] [fn. _ EventID] = fn ){
Delete obj. _ EventHandles [evt] [fn. _ EventID];
}
}
3. Correct the above method
The Code is as follows:
Function addEvent (obj, evt, fn, useCapture ){
If (obj. addEventListener) {// use W3C event registration first
Obj. addEventListener (evt, fn ,!! UseCapture );
} Else {
If (! Fn. _ EventID) {fn. _ EventID = addEvent. _ EventHandlesCounter ++ ;}
If (! Obj. _ EventHandles) {obj. _ EventHandles = [];}
If (! Obj. _ EventHandles [evt]) {
Obj. _ EventHandles [evt] = [];
If (obj ["on" + evt]) {
(Obj. _ EventHandles [evtype] [0] = obj ["on" + evtype]). _ EventID = 0;
}
Obj ["on" incluevtype+addevent.exe cEventHandles;
}
}
}
AddEvent. _ EventHandlesCounter = 1;
AddEvent.exe cEventHandles = function (evt ){
If (! This. _ EventHandles) {return true ;}
Evt = evt | window. event;
Var fns = this. _ EventHandles [evt. type];
For (var I = 0; I <fns. length; I ++ ){
If (fns [I] instanceof Function ){
Fns [I]. call (this );
}
}
};
Function delEvent (obj, evt, fn, useCapture ){
If (obj. removeEventListener) {// first remove the event handler using W3C
Obj. removeEventListener (evt, fn ,!! UseCapture );
} Else {
If (obj. _ EventHandles ){
Var fns = obj. _ EventHandles [evt];
If (fns) {delete fns [fn. _ EventID];}
}
}
4. Standardized event objects
The Code is as follows:
Function fixEvent (evt ){
If (! Evt.tar get ){
Evt.tar get = evt. srcElement;
Evt. preventDefault = fixEvent. preventDefault;
Evt. stopPropagation = fixEvent. stopPropagation;
If (evt. type = "mouseover "){
Evt. relatedTarget = evt. fromElement;
} Else if (evt. type = "mouseout "){
Evt. relatedTarget = evt. toElement;
}
Evt. charCode = (evt. type = "keypress ")? Evt. keyCode: 0;
Evt. eventPhase = 2;
Evt. timeStamp = (new Date (). getTime ();
}
Return evt;
}
FixEvent. preventDefault = function () {this. returnValue = false ;}
FixEvent. stopPropagation = function () {this. cancelBubble = true ;};
The fixEvent function is not executed independently. It must have an event object parameter and be executed only when an event occurs! The best way is to integrate it into execEventHandles of the addEvent function.
The Code is as follows:
AddEvent.exe cEventHandles = function (evt) {// traverses all event processing functions and executes
If (! This. _ EventHandles) {return true ;}
Evt = fixEvent (evt | window. event); // standardize it here
Var fns = this. _ EventHandles [evt. type];
For (var I = 0; I <fns. length; I ++ ){
If (fns [I] instanceof Function ){
Fns [I]. call (this, evt); // and use it as the first parameter of the event processing function
// In this way, the event object can be accessed in a unified way within the event handler function }}};
The above is a high handwriting. Below are some examples of actual listening tasks.
The Code is as follows:
<! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN">
<Html>
<Head>
<Title> test6.html </title>
<Script type = "text/javascript">
Function test (){
Window. alert ("You voted once ");
Document. getElementById ("1"). detachEvent ("onclick", test );
}
</Script>
</Head>
<Body>
<Input type = "button" value = "" id = "1"/>
<Script type = "text/javascript">
Document. getElementById ("1"). attachEvent ("onclick", test );
</Script>
</Body>
</Html>
Here we use document. getElementById ("1"). attachEvent ("onclick", test); for dynamic event binding, use
The Code is as follows:
Document. getElementById ("1"). detachEvent ("onclick", test)
Cancel the dynamic time, so that this event can only be matched once, and the next time you click this button, it will not produce any effect.
Next we will demonstrate listening to a keyboard event from time to determine whether the input is a number. If it is not a number, we will prompt it dynamically and reject the input.
Copy the Code as follows:
<! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN">
<Html>
<Head>
<Title> test7.html </title>
<Script type = "text/javascript">
Function test (event ){
// Each time a user presses a button, the user determines whether the number is correct.
If (event. keyCode <48 | event. keyCode> 57 ){
Window. alert ("You entered not a number ");
Return false;
}
}
</Script>
</Head>
<Body>
<Input type = "text" onkeypress = "return test (event);"/> enter a number
</Body>
</Html>
The event here is an event object, which can return a lot of information. For more information, see the relevant documentation.
Added: compatibility with event listening
1. IE uses the attachEvent/detachEvent method to add and delete event listeners. w3c uses the addEventListener/removeEventListener method.
2. IE uses the onevent naming method for its events, while w3c uses the event naming method.
3. the IE Event listener uses a global event object, while w3c passes the Event object as a parameter to the listener.
4. To avoid triggering default Event behaviors, the IE Method requires the programmer to set the returnValue attribute value in the Event object to false, while the w3c method is to execute the preventDefault method.
5. IE does not support the event capture phase.
6. To stop event transfer, IE sets the cancelBubble of the event object to true, while w3c sets the stopPropagation method.
7. IE calls the event listener as an independent function, while w3c calls the listener as an object method, this indicates that the this keyword in the event listener in ie points to a useless Global Object (window object) instead of an event occurrence object ).
8. There is a memory leakage problem in IE's use of event listeners. In IE, if you want to create an event listener for an element and use it in the listener, before the user enters other pages, the memory occupied by the listener and related DOM nodes will not be released.