Firing jQuery custom event without bubbling

I want to trigger a non-bumbling jQuery custom event for an object. I know that we can either use return false or stopPropagation to prevent bubbles. I want to know if I can trigger a custom event and indicate that it does not bubble by default.

This is the code that I have now

$(".abc").on("change", function () { var e = new $.Event("datachange"); $(this).trigger(e) }); 

The above event fires the datachange event on #abc and the event bubbles completely. I do not want it. I can achieve this using the following.

  $(".abc").on("change", function () { var e = new $.Event("datachange"); //e.stopPropagation(); this does not work $(this).trigger(e) }).on("datachange", function (e) { e.stopPropagation(); return false; }); 

I read that triggerHandler does something similar, but only for the first matching element.

Is there a better way to achieve this?

+8
jquery
source share
1 answer

You are correct that triggerHandler () applies only to the first element in the set, but this should not be a problem, because the set that you create with $(this) contains only one element.

Therefore, you can safely write:

 $(".abc").on("change", function() { $(this).triggerHandler("datachange"); }); 

Thus, the datachange event datachange not result in a bubble in the document tree.

+12
source share

All Articles