JavaScript Add listener and Delete listener usage detailed _javascript tips

Source: Internet
Author: User
Tags event listener

This article illustrates the use of JavaScript to add listening and deleting listeners. Share to everyone for your reference. The specific analysis is as follows:

JS in the event monitoring is to use AddEventListener to bind an event, this usage in jquery is very common and simple, but in the original JS is more complex, here the AddEventListener event of the various methods of testing and examples for everyone to reference learning.

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:

Copy Code code as follows:
$ ('. 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

Copy Code code as follows:
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
Copy Code code 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. Amendments to the above methods
Copy Code code as follows:
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
Copy Code code 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 only executed when the event occurs! The best way is to integrate it into the execeventhandles of the addevent function.

Copy Code code as follows:
Addevent.execeventhandles = function (evt) {//Traverse all event handler functions and Execute
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);//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

Copy Code code as follows:
<! 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
Copy Code code as follows:

document.getElementById ("1"). DetachEvent ("onclick", test)
The dynamic time of the cancellation, so that the event can only be appropriate once, the next time you click the button 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.
Copy Code code as follows:
<! 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>

Here is an event object, he can return a lot of information, please refer to the relevant documentation.

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, while the consortium is the name of the event.
3. The IE Event Listener uses a global event object, which is passed to the listener as a parameter 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 preventdefault is to execute the method.
5. IE did 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 calls the event listener as a separate function, and it is invoked as an object method in the global consortium, which means that the this keyword in IE is not pointing to an event occurrence object but to a useless global object (Window object).
8. IE has a memory leak problem with the use of event listeners. 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.

I hope this article will help you with your JavaScript programming.

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.