This content originally appeared on Go Make Things and was authored by Go Make Things
This week, we looked at how to create custom events with vanilla JS, and a helper function to make things a bit easier. Today, we’re going to look at different naming conventions for custom events.
To help prevent naming collisions, it’s a good idea to prefix custom events with your library or project name.
// Namespaced to the Calculator library
emit('calculator-add');
One common naming convention is kebab-case.
// kebab-case naming
emit('calculator-add');
Another convention is to put a colon (:
) between the library name and the event type. I’m personally quite fond of this approach, as I think it makes events more readable.
I call this style prefix-kebab.
// prefix-kebab naming
emit('calculator:add');
You can name custom events anything you want, but as a best practice, you should use all lowercase characters.
Event names are case-sensitive, and the property names on elements are case-insensitive and converted to lowercase by the browser. This can create conflicts if a developer uses on*
listeners on elements.
Because of these case-sensitivity issues, avoid camelCase.
// camelCase
// AVOID THIS
emitEvent('calculatorAdd');
Want to really dig in to topics like this? Check out my Vanilla JS Pocket Guides—short, focused ebooks and video courses made for beginners. Let's make {{year}} the year you master JavaScript!
This content originally appeared on Go Make Things and was authored by Go Make Things
Go Make Things | Sciencx (2022-08-12T14:30:00+00:00) Custom event naming conventions. Retrieved from https://www.scien.cx/2022/08/12/custom-event-naming-conventions/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.