简体   繁体   中英

How do you get the source element which fired an event when using an object method

When you do

event.addeventlistener("event", somefunction, false);

somefunction gets called with this set to the element on which the event fired and gets called with the event. However, event.target is not the same as this .

This makes for problems if I want to go for a more OO approach and put somefunction into my class and use bind , or make my class support the EventListener API. Because at that point, I'll be called with this set to the instance of my class. I can find no documented way of getting hold of that information.

event.target is the element what has triggered the event, while this the element what has the event listener registered on.

An Example:

In the script below, the a element has the listener. But whenever you click on the text inside the span it will become the target . From the target upwards, the event is given to all parent elements. This is called event bubbling .

 var e = document.getElementById('this'); e.addEventListener('click', function(event) { console.log('this: ', this); console.log('target:', event.target); }); 
 <a id="this" href="#"> <span id="target">click me</span> </a> 

If somefunction is a property of an object, and you want that object to be referenceable inside the function (via this ), then you can't use the same this for the element that triggered the event - somehow, you'll have to have the default this from inside the handler to the function. Here's one possibility, use an anonymous function that grabs the this and the event from inside the handler and calls the object's method with those as parameters:

 const obj = { bar(listenerElement, event) { console.log('this.data: ' + this.data); console.log('listener element ID: ' + listenerElement.id); console.log('event target ID: ' + event.target.id); }, data: 'data' } document.querySelector('#outer').addEventListener('click', function(event) { obj.bar(this, event); }, false); 
 <div id="outer"> <div id="inner">click me</div> </div> 

I have just discovered that an event object has a currentTarget property. which is precisely what the 'this' is set to. Couldn't find any documentation that said that explicitly though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM