jQuery .trigger() multiple events

前端 未结 4 1817
北海茫月
北海茫月 2020-12-29 23:22

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.

4条回答
  •  梦谈多话
    2020-12-30 00:09

    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");
    

提交回复
热议问题