This article describes the usage of adding and deleting listening in Javascript. Share it for your reference. The specific analysis is as follows:
Event listening in js is to use addEventListener to bind an event. This usage is very common and simple in jquery, but it is more complicated in native js. Here we organize tests and examples of various methods of addEventListener event for your reference and learning.
When I was working as a player two days ago, I encountered some trouble deleting the monitor and could not be deleted. After looking at it, I found that the parameters need to be fully corresponded. What does it mean to be completely corresponded? In other words:
The code copy is as follows: $('.video')[0].addEventListener('timeupdate', currentTimeHandler, true);
For example, three parameters need to be passed in this sentence so that it can be deleted. Why is it necessary? Yes, the painful part is here:
When adding and removing, the third parameter can be ignored, but their default situation is different at this time! !
Usually addEventListener is false...
1. Add custom event listening
The code copy is as follows: var eventHandlesCounter=1;//Calculate the number of added event listening, 0 is used as the reserved bit
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. Customize the listening of delete event
The code copy 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 copy is as follows: function addEvent(obj,evt,fn,useCapture){
if(obj.addEventListener){//Preferred to use W3C event registration
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"+evtype]=addEvent.execEventHandles;
}
}
}
addEvent.__EventHandlesCounter=1;
addEvent.execEventHandles = 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) {//Remove the event handler first using W3C method
obj.removeEventListener(evt,fn,!!useCapture);
}else {
if(obj.__EventHandles){
var fns = obj.__EventHandles[evt];
if(fns){delete fns[fn.__EventID];}
}
}
4. Standardize event objects
The code copy is as follows: function fixEvent(evt){
if(!evt.target){
evt.target = 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 separately, it must have an event object parameter, and it is executed only when the event occurs! The best way is to integrate it into the execEventHandles of the addEvent function.
Copy the code as follows: addEvent.execEventHandles = function (evt) {//Transize all event handling functions and execute
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 handler function
//In this way, you can use a unified method to access the event object within the event handler function} } };
The above is written by a master, and the following are some examples of actual monitoring events
Copy the code 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="vote" id="1"/>
<script type="text/javascript">
document.getElementById("1").attachEvent("onclick",test);
</script>
</body>
</html>
Here, document.getElementById("1").attachEvent("onclick",test); is used for dynamic event binding, and the copy code is used as follows:
document.getElementById("1").detachEvent("onclick",test) dynamically cancels time, so that this event can only be corresponding once, and no effect will be produced when clicking this button next time.
Next, another demonstration of a keyboard event that is timely monitored to determine whether the input is a number. If it is not a number, it will be prompted dynamically directly, and then reject its 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){
//Every time the user presses a key, he will determine whether it is a number
if(event.keyCode<48 || event.keyCode > 57){
window.alert("You are entering not a number");
return false;
}
}
</script>
</head>
<body>
<input type="text" onkeypress="return test(event);" />Please enter a number
</body>
</html>
The event here is an event object, which can return a lot of information. Please refer to the relevant documents for details.
Supplement: Compatibility in event monitoring
1. IE uses the attachEvent/detachEvent method to add and delete event listeners; w3c uses the addEventListener/removeEventListener method.
2. IE uses onevent naming method for its events, while w3c is the naming method for event.
3. The IE event listener uses a global Event object, while w3c passes the event object as a parameter to the listener.
4. In order to avoid triggering the default event behavior, IE's approach is to require programmers to set the returnValue property value in the Event object to false, while w3c's approach is to execute the preventDefault method.
5. IE does not provide support for the event capture phase.
6. To stop the event delivery, IE's approach is to set the cancelBubble of the event object to true, while w3c's approach is to set the execution stopPropagation method.
7. IE calls the event listener as an independent function, while in w3c it is called as an object method. This means that in ie, the this keyword in the event listener points to not the event occurrence object but a useless global object (window object).
8. IE has memory leak problems in using event listeners. In IE browser, if you want to create an event listener for an element and use that element in the listener, the memory space occupied by the listener and the associated DOM nodes will not be released before the user enters another page.
I hope this article will be helpful to everyone's JavaScript programming.