2

I'm building a publish/subscribe framework in jQuery and I'm wondering if there are performance penalties to triggering and listening to events on the document root?

All articles I can find describe the penalty you obviously get for listening to events on the document level, but triggering them from a more specific element - listening for a "click" for example.

My pseudo code:

$(document).on("myCustomEvent", function() {
    alert("Event triggered");
});
$(document).trigger("myCustomEvent");

My event does not have a fitting home in the DOM but I could always add a dummy element to trigger from/listen to if it's better, but would rather not. What do you think?

1 Answer 1

1

trigger() propagates up the DOM. It also interacts with all elements matching the object, which can cause conflicts / unexpected behavior. Neither of these are inherent* performance hits -- and since you're using a custom event, you shouldn't have an issue with other elements matching the object. That's really only a problem when trigger() is used with a real event, like trigger('click'). If you're concerned about either of these (bubbling up the DOM or other matching elements), you can use triggerHandler()

This post goes into more detail about the differences between trigger() and triggerHandler()

Sign up to request clarification or add additional context in comments.

1 Comment

how about namespacing his events too? -> $(..).trigger("ns.click")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.