I want to dispatch a CustomEvent on different occasions. Most examples on the net create and dispatch CustomEvents only once. I want to know how to do it correctly.
In this example the "A-Button" dispatches the same event over and over again.
The "B-Button" creates a new CustomEvent
each time, the event should be dispatched.
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);
});
<button onclick="a()">A</button>
<button onclick="b()">B</button>
<div id="targetA"></div>
<div id="targetB"></div>
Sideeffects of the A approach could be that the timestamp is not updated. This could lead to unexpected behaviour on handlers that depend on the timestamp.
The B approach could be less performant, since the CustomEvent object is instanciated over and over again. (Memory should not be a problem.)
Is there a "correct" way, or are there any best practices?