JavaScript dispatch CustomEvent: new or reuse
Asked Answered
E

0

8

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?

Enquire answered 14/6, 2017 at 5:48 Comment(1)
I would go with the 'B'-approach as it would allow to pass realtime or should say, fresh , and 'separate' data to each handler in response to the event and also if we attempt to pass data through the 'A'-approach and the handler then mutates the data, all handlers will be affected too!..... more on creating and triggering event on MDNGilbye

© 2022 - 2024 — McMap. All rights reserved.