Last Updated: February 25, 2016
·
339
· jamesallardice

Remember that .one() can delegate event handlers too!

The .one() method in jQuery is used to bind an event handler to an element and automatically unbind that event handler after it has executed a single time.

The .on() method is commonly used to delegate an event handler further up the DOM tree (which is more efficient than binding a handler to many individual elements and also allows us to handle elements that don't exist in the DOM at the time of the binding).

It's commonly forgotten that the .one() method also supports event delegation in the same way .on() does. So if you need to bind an one-off event handler to an element that doesn't exist in the DOM at the time your code runs:

$("#someAncestor").one("click", ".boundTo", function () {
    // Do something cool
});

Bonus tip: don't call .one() or .on() on the document object if you can help it. The less distance the event has to bubble before triggering the handler, the more efficient your delegation will appear.