Binding way up the DOM tree
One habit I’ve developed since I’ve been into a lot more front-end development is using jQuery to bind to events way up the DOM tree along with filter selectors to make sure the handlers are only fired on the right elements.
Why do this? Primarily because dynamically loaded HTML content will not get events bound to
by jQuery unless I explicitly bind again—it’s worth noting that the
method in jQuery is supposed to do this as well, but it has been deprecated
So how does this work? Let’s say we have simple click binding like:
Binding it up the DOM we would instead bind it like this:
You can also bind to
$(document), but I believe (don’t quote me) there are
some events—possibly just for some browsers—that do not bubble up to
document correctly but do bubble up to
body. Also as I understand it, there
are a couple of events—again I think only on some browsers and these may be
bugs—that still don’t bubble up at all. So you may need to adapt this
approach in certain circumstances. In general, I’ve found this to work on
modern browsers everywhere I’ve used it (I’m not targeting IE8 at the moment).
Though, jQuery may have some internal magic to ensure it does work most of the time.
By binding this way event, we will always be able to intercept the events even if it comes from elements that have been added to the DOM dynamically after we’ve bound the event handlers. This is really useful if we are using something like PJAX to handle navigation without full page loads.
Namespacing your events
By binding in this way our components and plugins can bind and unbind their events without unbinding event handlers attached by other parts of the code.
1 2 3 4 5 6 7 8
Triggering events for a specific namespace is probably not a very common scenario but it’s good to know you can do it if you need to.
Bind to your events using conventions with classes and the data-api
Being able to automatically bind things based on conventions is a lot cleaner (imo) than explicitly binding or using jQuery extension methods. This is, again, another technique commonly seen in the Bootstrap components but I like it so I’ve stolen it as well.
1 2 3 4 5 6 7 8 9 10 11
1 2 3 4 5
You could also do this using only the classes, for example binding to
.btn-toggle and determining state from
.is-enabled. and skip the data-api
altogether. I’m not really sure there is any real benefit in using the
data-api, but arguably it is seperating the markup that hooks the element into
If you don’t feel this seperation is important to you feel free not to use it.