Javascript: add and remove listening

  • 2020-05-07 19:15:24
  • OfStack

This article illustrates the use of Javascript to add and remove listeners. Share with you for your reference. Specific analysis is as follows:

In js, event monitoring is to bind one event with addEventListener. This usage is very common and simple in jquery, but more complicated in native js. Here, we have sorted out the tests and examples of addEventListener event methods for your reference.

When I was doing the player two days ago, I found 1 trouble to add the monitor and then delete the monitor, so I couldn't delete it. Later, I looked at 1 and found that the parameters need to be exactly corresponding to each other.

$('.video')[0].addEventListener('timeupdate', currentTimeHandler, true);

For example, in this sentence, we need to pass in 3 parameters, so that we can delete.
In add and remove, the third parameter can indeed not be written, but their default is not the same!!

addEventListener is false...
1. Add custom event listener

var eventHandlesCounter=1;// Count the number of added event listeners, 0 Reserved space 
    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 delete event listener
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. Fix the above method
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) {// Use the first W3C Method to remove the event handler         
       obj.removeEventListener(evt,fn,!!useCapture);
   }else {
      if(obj.__EventHandles){
         var fns = obj.__EventHandles[evt];
         if(fns){delete fns[fn.__EventID];}
      }
}

4. Standardize event objects
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 argument, and it is only executed when an event occurs! The best way to do this is to incorporate it into the execEventHandles of the addEvent function.

addEvent.execEventHandles = function (evt) {// All event handlers are traversed and executed 
if (!this.__EventHandles) {return true;}
evt = fixEvent(evt || window.event);// Here it is standardized
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 as the first of the event handler functions 1 A parameter
// This allows you to use a series within the event handler 1 Method to access the event object } } };

Above is the master to write, the following sorting out a few actual listening to the case of things

<!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 threw 1 Tickets again ");
   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>

document.getElementById ("1").attachEvent ("onclick",test); Dynamic event binding, use

document.getElementById("1").detachEvent("onclick",test)
Cancel the dynamic time, so that the event only corresponds to 1 time, the next time the button is clicked, there will be no effect.
Here is another example of monitoring keyboard events to determine whether the input is a number or not. If it is not a number, then reject the input
<!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 1 Button, to determine whether it is a number
   if(event.keyCode<48 || event.keyCode > 57){
    window.alert(" What you typed is not 1 A digital ");
    return false;
   }
  }
 </script>
  </head>
 
  <body>
    <input type="text" onkeypress="return test(event);" /> Please enter a number
  </body>
</html>

Here, event is an event object, which can return a lot of information, please refer to the relevant documents for details.
 
supplement: event listening compatibility with

1. IE USES the attachEvent/detachEvent method to add and remove event listeners; w3c USES the addEventListener/removeEventListener method.
2. IE names its events onevent and w3c event.
3. A global Event object is used in the IE event listener, while w3c passes the event object as a parameter to the listener.
4. To avoid triggering the default event behavior, IE requires the programmer to set the returnValue attribute value in the Event object to false, while w3c executes the preventDefault method.
5. IE does not provide support for the event capture phase.
6. To stop the event delivery, IE sets the cancelBubble of the event object to true, while w3c sets the stopPropagation method to execute.
7. IE calls the event listener as a separate function, while w3c calls it as an object method, which means that in ie, the this keyword in the event listener points to a useless global object (window object) instead of an event occurrence object.
8. IE has a memory leak problem with the use of event listeners. In the 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 that listener and the associated DOM node will not be freed until the user enters another page.

I hope this article has been helpful to your javascript programming.


Related articles: