Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
340 views
in Technique[技术] by (71.8m points)

javascript - event currentTarget changes after setTimeout

consider:

let sel=document.getElementById('mys');

sel.onchange=function(e) {
  console.log(e.currentTarget===null); // false
  setTimeout(e => {
     console.log(e.currentTarget===null); // true
  }, 0, e);
 }
<select id="mys">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Inspired by Joseph Marikle's comment, I found the real cause:

DOM Standard § 2.9. Dispatching events describes the algorithm, which I'm partially reproducing here:

To **dispatch** an event to a target […] run these steps:
[…]
5. If target is not relatedTarget or target is event’s relatedTarget, then:
    […]
    9. While parent is non-null:
        […]
        8. Otherwise, set target to parent and then:
            […]
        9. If parent is non-null, then set parent to the result of invoking parent’s get the parent with event.
        […]
    […]
    12. Set event’s eventPhase attribute to CAPTURING_PHASE.
    […]
    14. For each tuple in event’s path, in reverse order:
        1. […] invoke […]
    15. For each tuple in event’s path, in order:
        1. If tuple’s target is non-null, then set event’s eventPhase attribute to AT_TARGET.
        2. Otherwise, set event’s eventPhase attribute to BUBBLING_PHASE.
        3. […] invoke […]
[…]
6. Set event’s eventPhase attribute to NONE.
7. Set event’s currentTarget attribute to null.
[…]

To **invoke** […] run these steps:
[…]
5. Initialize event’s currentTarget attribute to struct’s invocation target.
[…]

So, after the event has finished processing all phases (capture, at_target, bubbling), then currentTarget gets assigned null.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...