Custom events; event name and options

Hi! From what I have noticed so far, it’s very common to have a more explicit event name such as example A.

Example A

const event = new CustomEvent("koalacollapsible:expanded", {
  detail: {
    id: "collapsible-1",
  }
});

That makes me wonder what are the downsides of creating custom event like Example B?

Example B

const event = new CustomEvent("koalacollapsible", {
  detail: {
    id: "collapsible-1",
    isExpanded: true,
  }
});

Please kindly share your knowledge on this. Thank you!

Hi :slight_smile:!

Example B it’s mostly a problem when You’re working with other people or You’re expecting the software to be used/integrated with third party software.

For example, imagine You have two plugins that trigger/fire the same event, collapsible; both plugins would try to handle the event, but only one would succeed and the other may throw an exception, which in turn may take down the entire application.

IMHO, a good practice would be to use namespaces. If Your plugin name is MyAwesomePlugin, a namespace would be myawesomeplugin:verb:action where verb would be collapsible and action would be expanded. I know, this is verbose, but unless You’re absolutely certain that Your software will not be used with 3rd party software, namespaces would be a good alternative (there may be others).

By the way, this is all thinking in the global context, since events, depending on the language, may be scoped to the local context.

Hope it helps :slight_smile:.

Thanks @skaparate!

I understand about the namespace practice. I had actually forgotten to include the namespace in my examples. I have updated my examples with it.

One thing I can think of about Example B is that it would require a check to find out what is the exact action before proceeding to something else. As for Example A, it is more straight forward since the event name is more verbose.

Am just wondering if there’s anything else apart from that.

1 Like

Yes, but unless I misunderstood Your point (sorry if that’s the case :sweat_smile:), we usually don’t trigger the same event for different purposes. I mean, when we use the JavaScript API event click (or onclick, depending on how it’s used), we expect it to be fired only for clicks and not for a key event (although a programmer may override the behavior :stuck_out_tongue:).

Basically, you should name the events for when they’re expected to be fired, this way Your software would follow some pattern and it will be easier for other to even guess what the event names are.

I can’t think of anything else either.

You got my point :slight_smile:

1 Like