DOM: element. addeventlistener

Source: Internet
Author: User
DOM: element. addeventlistener From MDC

«Gecko DOM reference

Contents

[Hide]

  • 1 Summary
  • 2 Syntax
  • 3 Example
  • 4 Notes
    • 4.1 Why use addeventlistener?
    • 4.2 Adding a listener during event dispatch
    • 4.3 Multiple identical Event Listeners
    • 4.4 The value of this within the Handler
    • 4.5 Internet Explorer
    • 4.6 Older way to register Event Listeners
    • 4.7 Memory issues
  • 5 Specification

[Edit] Summary

AddeventlistenerAllows the registration of event listeners on the event Target. An event target may be a node in a document,DocumentItself,Window, OrXMLHttpRequest.

[Edit] Syntax
 
Target. Addeventlistener (Type,Listener,Usecapture);
Type
A string representing the event type to listen.
Listener
The object that calls es a notification when an event of the specified type occurs. This must be an object implementing Eventlistener Interface, or simply a javascript Function .
Usecapture
If True, UsecaptureIndicates that the user wishes to Initiate capture. After initiating capture, all events of the specified type will be dispatched to the registered ListenerBefore being dispatched to any EventtargetS beneath it in the DOM tree. events which are bubbling upward through the tree will not trigger a listener designated to use capture. See Dom Level 3 events For a detailed explanation.

[Edit] Example
     DOM Event example      
   
  
one
two

In the above example,Modifytext ()Is a listenerClickEvents registered usingAddeventlistener (). A click anywhere on the table will bubble up to the handler and runModifytext ().

[Edit] Notes

[Edit] Why use Addeventlistener?

AddeventlistenerIs the way to register an event listener as specified in W3C Dom. Its benefits are as follows:

    • It allows adding more than a single handler for an event. This is Special usefulDHTMLLibraries orMozilla extensionsThat need to work well even if other libraries/extensions are used.
    • It gives you finer-grained control of the phase when the listener gets activated (capturing vs. bubbling)
    • It works on any dom element, not just HTML elements.

The alternative,Older way to register Event ListenersIs described below.

[Edit] Adding a listener during event dispatch

IfEventlistenerIs added toEventtargetWhile it is processing an event, it will not be triggered by the current actions but may be triggered during a later stage of event flow, such as the bubbling phase.

[Edit] Multiple identical Event Listeners

If multiple identicalEventlistenerS are registered on the sameEventtargetWith the same parameters, the duplicate instances are discarded. They do not causeEventlistenerTo be called twice, and since the duplicates are discarded, they do not need to be removed manually withRemoveeventlistenerMethod.

[Edit] The value ThisWithin the Handler

It is often desirable to reference the element from which the event handler was fired, such as when using a generic handler for a series of similar elements. When attaching a function usingAddeventlistener ()The valueThisIs changed-note that the valueThisIs passed to a function from the caller.

In the example above, the valueThisWithinModifytext ()When called from the click event is a reference to the table 'T'. This is in contrast to the behavior that occurs if the handler is added in the HTML source:

 
<Table id = "T" onclick = "modifytext ();">...

The valueThisWithinModifytext ()When called from The onclick event will be a reference to the global (window) object.

[Edit] Internet Explorer

In Ie you have to useAttacheventRather than the standardAddeventlistener. To support ie, the example abve can be modified:

 
If (El. addeventlistener) {el. addeventlistener ('click', modifytext, false);} else if (El. attachevent) {el. attachevent ('onclick', modifytext );}

[Edit] Older way to register Event Listeners

Addeventlistener ()Was introduced with the DOM 2EventsSpecification. Before then, event listeners were registered as follows:

 
// Using a function reference-note lack of '()' El. onclick = modifytext; // using a function expressionelement. onclick = function (){... statements ...};

This method replaces the existingClickEvent listener (s) on the element if there are any. Similarly for other events and associated Event Handlers suchBlur(Onblur),Keypress(Onkeypress), And so on.

Because it was essential part of Dom 0, this method is very widely supported and requires no special cross-browser code; hence it is normally used to register listeners dynamically unless the extra featuresAddeventlistener ()Are needed.

[Edit] Memory issues

A common way for one to stumble upon increasing memory problems is to pass an object's method as a callback:

SetTimeout (obj. func, 1000); // sets wrong | this |! Document. addeventlistener ("LOAD", obj. func, false); // sets wrong | this |!

A simple workaround is to pass an anonymous function as a callback:

 
Document. addeventlistener ("LOAD", function (event) {obj. func (event) ;}, false );

note that this anonymous function has access to all variables in its enclosing environment, and the memory these variables use may not be reclaimed by the JavaScript engine as long as the anonymous function might be used (I. e. the event listener is registered ). while only OBJ need actually be preserved for the function, an engine might choose to preserve other variables, too, increasing memory overhead. calling removeeventlistener or removing all references to an anonymous function will allow the variables 'memory to be reclaimed, and you shoshould be careful to do so to allow unused memory to be efficiently reclaimed by the JavaScript engine.

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.