jQuery events have a namespace concept built in for easy and safe unbinding of just the events you've added.
These namespaces, however, don't prevent collisions when different plugins trigger the same basic event. For example, if plugin A triggers the hide.foo
event and plugin B triggers the hide.bar
event, any handler listening for the hide
event is going to be invoked twice, even with the namespaces.
This can cause problems when plugins trigger overly generic names like open
, close
, show
, hide
, start
, end
, etc., yet so many plugins out there (even ones from large libraries like jQueryUI and bootstrap) trigger these generic events without a second level namespace.
So here's my question. It seems like a second level of namespacing would be prudent, both to distinguish your events from other plugins and from standard DOM events. The convention could be something like namespace:eventName
or namespace:eventName.secondaryNamespace
if using the standard jQuery dot notation.
But nobody seems to be doing this, so I wonder if there's some compelling reason not to. Does anybody know?
Update:
To provide a more concrete example, suppose I'm using plugin A which triggers the show
and hide
events on tooltips as the user hovers over certain text. Since events propagate and my DOM is constantly changing, I decide to bind my event listener to the document
element to catch the show
and hide
events from all tooltips.
Then, a few weeks later, I add plugin B to my app which also triggers the hide
event after the user dismisses an alert message. Now all of the sudden my tooltip code is going to be invoked more than I want it to because both the tooltip and the alert message plugins are triggering events with the same name.
It turns out that both libraries I specifically mentioned (jQueryUI and Bootstrap) either do or are planning on prefixing their custom events.
Here's what jQueryUI does in its custom _trigger
method:
event.type = ( type === this.widgetEventPrefix ? type : this.widgetEventPrefix + type ).toLowerCase();
This allows you to define your own prefix via this.widgetEventPrefix
on any included widget or widget you make with the widget factory.
Bootstrap hasn't implemented a prefix yet but plans on doing it in the next major version (3.0.0).
Here is what @fat said in this Github issue:
In the future we'll probably namespace everything with bootstrap (data-attrs and events - but that will be a 3.0.0 thing, because it's breaks backwards compatibility)
And here is his tweet in response to my question about it.
--
As for me, I've decided to name my custom events with one of the following patterns (depending on context) to avoid any possible conflicts with other libraries in the future.
prefix:event.namespace
appname:widgetname:event.namespace
libraryname:widgetname:event.namespace
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With