JavaScript 调度 CustomEvent:新建或重用

hth*_*tho 5 javascript dispatch custom-events

我想在不同的场合分派 CustomEvent。网络上的大多数示例只创建和分派 CustomEvents 一次。我想知道如何正确地做到这一点。

在这个例子中,“A-Button”一遍又一遍地分派相同的事件。“B-Button”new CustomEvent每次创建一个,应该调度事件。

var targetA = document.getElementById('targetA');
var targetB = document.getElementById('targetB');

var evtA = new CustomEvent("myEvent");

function a(){
  targetA.dispatchEvent(evtA);
}

function b(){
  targetB.dispatchEvent(new CustomEvent("myOtherEvent"));
}

targetA.addEventListener("myEvent", function(e){
  console.log(e);
  console.log(e.timeStamp);
});

targetB.addEventListener("myOtherEvent", function(e){
  console.log(e);
  console.log(e.timeStamp);
});
Run Code Online (Sandbox Code Playgroud)
<button onclick="a()">A</button>
<button onclick="b()">B</button>
<div id="targetA"></div>
<div id="targetB"></div>
Run Code Online (Sandbox Code Playgroud)

A 方法的副作用可能是时间戳未更新。这可能会导致依赖时间戳的处理程序出现意外行为。

B 方法的性能可能较低,因为 CustomEvent 对象被一遍又一遍地实例化。(内存应该不是问题。)

有没有“正确”的方法,或者有什么最佳实践?