Reputation: 3077
I want to trigger a non-bubblable custom jQuery event on an object. I know we can either use return false or stopPropagation to prevent bubbling. What I want to know is can I trigger a custom event and specify that by default it does not bubble.
This is the code I have now
$(".abc").on("change", function () {
var e = new $.Event("datachange");
$(this).trigger(e)
});
The above triggers the datachange event on #abc and bubbles the event all the way up. I don't want that. I can achieve that by 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?
Upvotes: 11
Views: 7226
Reputation: 262979
You are right that triggerHandler() only applies to the first element in the set, but that should not be a problem because the set you build with $(this)
only contains one element.
Therefore, you can safely write:
$(".abc").on("change", function() {
$(this).triggerHandler("datachange");
});
That way, the datachange
event will not bubble up the document tree.
Upvotes: 17