Home > Web Front-end > JS Tutorial > Detailed explanation of how to add and delete listeners using Javascript_javascript skills

Detailed explanation of how to add and delete listeners using Javascript_javascript skills

WBOY
Release: 2016-05-16 16:25:40
Original
1735 people have browsed it

The example in this article describes the use of Javascript to add and delete listeners. Share it with everyone for your reference. The specific analysis is as follows:

Event monitoring 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 are the tests and examples of each method of the addEventListener event for your reference.

When I was working on the player two days ago, I encountered a little trouble after adding and deleting the monitor. I couldn’t delete it. After looking at it, I found that the parameters need to be completely corresponding. What does complete correspondence mean? In other words:

Copy code The code is as follows:
$('.video')[0].addEventListener('timeupdate', currentTimeHandler , true);

For example, in this sentence, three parameters need to be passed in so that it can be deleted. Why must it be like this? Yes, the painful part is here:
When adding and removing, the third parameter does not need to be written, but their default conditions are different at this time! !

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

Copy code The code is as follows:
var eventHandlesCounter=1;//Count the number of event listeners added, 0 as a 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[i].call(this);
}
}

2. Customize deletion event monitoring
Copy code 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. Modify the above method
Copy code The code is as follows:
function addEvent(obj,evt,fn,useCapture){
    if(obj.addEventListener){//优先使用W3C事件注册
       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        if(fns[i] instanceof Function){
           fns[i].call(this);
       }
    }
};
function delEvent(obj,evt,fn,useCapture){
   if (obj.removeEventListener) {//先使用W3C的方法移除事件处理函数        
       obj.removeEventListener(evt,fn,!!useCapture);
   }else {
      if(obj.__EventHandles){
         var fns = obj.__EventHandles[evt];
         if(fns){delete fns[fn.__EventID];}
      }
}

4、标准化事件对象
复制代码 代码如下:
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;};

fixEvent函数不是单独执行的,它必须有一个事件对象参数,而且只有事件发生时它才被执行!最好的方法是把它整合到addEvent函数的execEventHandles里面。

复制代码 代码如下:
addEvent.execEventHandles = function (evt) {//遍历所有的事件处理函数并执行
if (!this.__EventHandles) {return true;}
evt = fixEvent(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,evt);//并且将其作为事件处理函数的第一个参数
//这样在事件处理函数内部就可以使用统一的方法访问事件对象了 } } };

上面是高手写了,下面整理几个实际的监听事情的例子

复制代码 代码如下:



test6.html








Here, document.getElementById("1").attachEvent("onclick",test); is used for dynamic event binding, and
is used to copy the code The code is as follows:

document.getElementById("1").detachEvent("onclick",test)
Cancel the dynamic time, so that this event can only be responded to once, and the button will not be clicked again next time What effect does it produce.
Below is another demonstration of monitoring keyboard events at all times to determine whether the input is a number. If it is not a number, it will prompt dynamically and then reject the input
Copy code The code is as follows:



test7.html




Please enter a number


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 remove 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 to the listener as a parameter.
4. In order to avoid triggering the default event behavior, IE requires programmers to set the returnValue attribute 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 delivery of events, IE's approach is to set the event object's cancelBubble to true, while w3c's approach is to set and execute the stopPropagation method.
7. IE calls the event listener as an independent function, but in w3c it is called as a method of the object. This means that the this keyword in the event listener in IE points not to the event object but to an object. Useless global object (window object).
8. IE has a memory leak problem in using event listeners. In IE browser, if you want to create an event listener for an element and use the element in the listener, the memory space occupied by the listener and related DOM nodes will not be occupied before the user enters other pages. be released.

I hope this article will be helpful to everyone’s JavaScript programming design.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template