1

Is there any reason not to define custom properties on an Event object in JavaScript for the most part?

I am dispatching my own event on the window object and I want to add relevant properties to the event object.

Is it frowned upon to define custom properties on an Event object in JavaScript? A frown or grimace?

var infoEvent = new Event("info");
infoEvent.message = message;
infoEvent.referenceID = id;
window.dispatchEvent(infoEvent);

It is not guaranteed to have ES5 or ES6.

Looks like an alternative was suggested in a comment to use a CustomEvent.

1.21 gigawatts
  • 16,517
  • 32
  • 123
  • 231
  • 2
    Maybe look at the [CustomEvent](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent) api . – Dylan Landry May 27 '20 at 01:11
  • 4
    The only problem would be if you somehow overwrite a well defined property name and some script was also listening to this event and expecting this well defined property to be something else, but... is it really a problem? – Kaiido May 27 '20 at 01:13
  • 1
    Yes, you can assign custom properties to Objects. – StackSlave May 27 '20 at 01:17
  • I would say it's generally frowned upon to modify global objects. Instead, use custom objects/classes. – Matthew Herbst May 27 '20 at 01:18
  • 2
    @MatthewHerbst `infoEvent` is not a global object, that's an Event **instance**. No other object will be modified. – Kaiido May 27 '20 at 01:21
  • I'm aware. I would say it's still frowned upon. – Matthew Herbst May 27 '20 at 01:24
  • @MatthewHerbst If you found this code somewhere you would frown but would you change it? – 1.21 gigawatts May 27 '20 at 05:22
  • 1
    @DylanLandry It looks like CustomEvents are for this purpose. Never heard of them until now. Maybe could you make that an answer? And reopen this question? – 1.21 gigawatts May 27 '20 at 05:27
  • Possible duplicate of [Javascript: Declare custom event with custom properties](https://stackoverflow.com/q/58953249/1048572) – Bergi May 27 '20 at 10:39

1 Answers1

2

No, you should never define custom properties on DOM objects. There are many properties on the Event interface, and even if you don't collide with any of them now there might be additional ones in the future. Notice there already is an MessageEvent interface and even a MediaKeyMessageEvent that does have a .message property.

The proper way to attach custom data to custom DOM events is to use the CustomEvent API and put the data on its .detail property (which you can initialise from the constructor).

Bergi
  • 630,263
  • 148
  • 957
  • 1,375