【问题标题】:Execution order with nested event handlers [duplicate]嵌套事件处理程序的执行顺序[重复]
【发布时间】:2020-11-29 20:26:59
【问题描述】:

检查这个简单的例子:

function doit() {
  const button = document.querySelector('button');

  button.addEventListener('click', (e) => {
    dispatchFoo();
    console.log('click listener executed');
  })
  
  document.addEventListener('foo', handleFoo);

  button.click();

  console.log('end reached')
}

function handleFoo() {
  console.log('foo listener executed');
}

function dispatchFoo() {
  const event = new CustomEvent('foo');
  document.dispatchEvent(event);
}

console.clear();
doit();
<button>button</button>

这个输出(如我所料):

foo listener executed
click listener executed
end reached

我可以依赖这个执行顺序吗?

【问题讨论】:

    标签: javascript event-loop order-of-execution


    【解决方案1】:

    是的,EventTarget.dispatchEvent() 同步调度事件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-27
      • 1970-01-01
      • 2021-05-02
      • 1970-01-01
      • 2012-02-20
      • 2011-03-28
      • 2012-05-27
      • 1970-01-01
      相关资源
      最近更新 更多