Introduction to the use of Javascript to add listening and deleting listeners

Source: Internet
Author: User
Tags event listener

In the first two days when you do the player to add a listener after the deletion of the monitor encountered a bit of trouble, deleted, and then looked at the only found that the parameters need to be completely corresponding, what is called the exact corresponding, in other words:

The code is as follows Copy Code

$ ('. Video ') [0].addeventlistener (' Timeupdate ', Currenttimehandler, true);

such as this sentence, need to pass three parameters, so that can be deleted, why must this, yes, the place where the egg hurts is here:
When add and remove, the third argument does not write, but at this point their default is not the same!!!

Usually the AddEventListener is false ...

1. Add custom Event Listener

The code is as follows Copy Code
var eventhandlescounter=1;//statistics Add Event Listener number, 0 as 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, custom Delete event monitoring

The code is as follows Copy Code

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. Amendments to the above methods

The code is as follows Copy Code

function Addevent (obj,evt,fn,usecapture) {
if (Obj.addeventlistener) {//preferred use of the 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 event handler by first using the method of the Consortium
Obj.removeeventlistener (EVT,FN,!! Usecapture);
}else {
if (obj.__eventhandles) {
var FNS = obj.__eventhandles[evt];
if (FNS) {delete Fns[fn.__eventid];}
}
}

4, the Standardization of event objects

The code is as follows Copy Code

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 only executed when the event occurs! The best way is to integrate it into the execeventhandles of the addevent function.

The code is as follows Copy Code

Addevent.execeventhandles = function (evt) {//Traverse all event handler functions and execute if (!this.__eventhandles) {return Tru e;}
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);//And as the first argument to the event handler function
This enables the use of uniform methods to access the event object's}} within the event handler function;


The above is the master wrote, the following to tidy up a few practical examples of monitoring things

  code is as follows copy code

<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
<title>test6.html</title>
<script type= "Text/javascript" >
function Test () {
Window.alert ("You vote once");
document.getElementById ("1"). DetachEvent ("onclick", test);
}
</script>

<body>
<input type= "button" value= "Vote" id= "1"/>
<script type= "Text/javascript" >
document.getElementById ("1"). Attachevent ("onclick", test);
</script>
</body>

This uses document.getElementById ("1"). Attachevent ("onclick", test); Dynamic event binding, using the

document.getElementById ("1"). DetachEvent ("onclick", test) to cancel the dynamic time, so that the event can only be a corresponding,

Click this button again when it will not have any effect.

Here's another example of listening to a keyboard event at a time, judging whether the input is a number, if it's not a number, and then rejecting its input.

The code is as follows Copy Code

<pre name= "code" class= "HTML" ><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
<title>test7.html</title>
<script type= "Text/javascript" >
function test (event) {
Each button is pressed to determine whether the number
if (event.keycode<48 | | event.keycode > 57) {
Window.alert ("You are not entering a number");
return false;
}
}
</script>


<body>
<input type= "text" onkeypress= "return Test (event);"/> Please enter a number
</body>
</pre><br>
Here is an event object, he can return a lot of information, please refer to the documentation. <p></p>
<pre></pre>
<p></p>

Supplemental: event-monitoring compatibility

1,ie uses the Attachevent/detachevent method to add and remove event listeners, and the Addeventlistener/removeeventlistener method is used by the consortium.

2,ie uses the OnEvent naming method for its events, and the consortium is the name of the event.

The 3,ie event Listener uses a global event object, which is passed as an argument to the listener by the consortium.

4, in order to avoid triggering the default event behavior, IE's practice is to require the programmer to set the ReturnValue property value in the event object to False, and the practice of the consortium 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 practice is to set the event object's cancelbubble to true, and the practice of the consortium is to set the execution Stoppropagation method.

7,ie the event listener as a separate function, which is invoked as an object's method, which means that in IE the this keyword in the event listener points not to an event occurrence object but to a useless global object (Window object).

8,ie There is a memory leak problem with the event listener. In IE Explorer, 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 is not freed until the user enters another page.

All right, here we are. About the JS event monitoring and cancellation method is introduced here Oh, welcome to comment.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.