更新时间:2023-09-29 09:33:13
(function($) {
$.fn.triggerAll = function(topics, data, delimiter) {
return this.each(function() {
var $this = $(this), chain = [], t = '';
delimiter = (delimiter || '.');
// rebuild chain
$.each(topics.split(delimiter), function(i,n) {
t += (i == 0 ? '' : delimiter) + n;
chain.push(t);
});
// append/prepend original topic?
data = (data || []);
data.push(topics);
$.each(chain, function(i,t) {
$this.trigger(t, data);
});
});
};
})(jQuery);
当然,由于jQuery处理触发命名空间的方式,因此触发"root"事件实际上会触发命名空间版本,因此要获得所需的结果,您需要使用另一个字符作为分隔符,例如/
,然后声明您的事件,例如:
Granted, due to how jQuery handles triggering namespacing, triggering the "root" event actually fires the namespaced versions, so to get what you expect you'd need to use another character for the delimiter, like /
, and then declare your events like:
var $o = $('#whatever');
// this will be triggered for all events starting with 'root'
$o.on('root', function () { console.log(Array.prototype.slice.call(arguments, 0)); });
// some arbitrary way to fire custom events
$o.on('click', function () {
$o.triggerAll('root/custom1/subA', ['1st', '2nd'], '/');
$o.triggerAll('root/custom2', [3, 4, 5], '/');
});