Use more ergonomic custom events

While we have CustomEvent for all of our events that needs to carry data the need for the detail property nesting can feel a bit cumbersome.

Also the name custom in CustomEvent does not really tell us much about what this object does.

DataEvent

I find it useful to instead inherit from Event and then simply use Object.assign to append properties from the provided options.

class DataEvent extends Event {
  constructor(name, options = {}) {
    super(name);
    Object.assign(this, options);
    Object.freeze(this);
  }
}

Also we freeze the object as the event should not be modified.

Usage example:

const notification = new DataEvent('notification', {message: 'Our message'});

console.log(notification.message); // Logs: Our message

This is obviously has some limitations as some properties (such as target, isTrusted, eventPhase) on an event should and cannot be overridden, but I feel that collisions are really rare and also an error will also be thrown in these cases.

All in all I think this small class gives us a bit more ergonomic generic events.

More specific events

You might of course also consider creating events with even more specific names and then skipping the first name property in the name property.

class Notification extends Event {
  constructor(options = {}) {
    super(this.constructor.name);
    Object.assign(this, options);
    Object.freeze(this);
  }
}

Have a nice and eventful day!