I'm writing a jQuery plugin and using .on
and .trigger
as my pub/sub system. However, I want to trigger multiple events in different scenarios.
Is this possible to do as one string, like the .on
method?
Goal:
$this.trigger("success next etc"); // doesn't work
Current solution:
$this .trigger("success") .trigger("next") .trigger("etc"); // works, triggers all three events
Any suggestions?
JQuery itself does not support triggering multiple events, however you could write custom extension method triggerAll
(function($) { $.fn.extend({ triggerAll: function (events, params) { var el = this, i, evts = events.split(' '); for (i = 0; i < evts.length; i += 1) { el.trigger(evts[i], params); } return el; } }); })(jQuery);
And call it like following:
$this.triggerAll("success next etc");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With