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?

Peter
  • 33
  • 1
  • 4

1 Answers1

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()

Community
  • 1
  • 1
devlin carnate
  • 8,309
  • 7
  • 48
  • 82