绑定到自定义jquery事件的所有命名空间 [英] Bind to all namespaces of custom jquery event

查看:74
本文介绍了绑定到自定义jquery事件的所有命名空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试收听一个自定义事件,但我想有效地忽略它的命名空间或以某种方式监听所有命名空间而不单独定义它们这一事实。

I'm trying to listen for a custom event but I would like to effectively 'ignore' the fact that it's namespaced or somehow listen to all namespaces without defining them individually.

$('#test').on('custom', ...);

$('#test').trigger('custom.namespace1');
$('#test').trigger('custom.namespace2');

我希望能够做到这一点的原因是因为我有多个ui插件可以触发事件他们被隐藏/显示。这些事件主要在内部使用,但是命名空间,因此它们不会相互冲突。但是我也想知道什么时候隐藏一个特定的ui元素,独立于其来源执行其他清理逻辑。

The reason I want to be able to do this is because I have multiple ui plugins that fire events when they are hidden/shown. These events are mainly used internally but are namespaced so they don't collide with each other. However I would also just like to know when a particular ui element is hidden, independent of its source to perform other cleanup logic.

在上面的例子中,什么都不会发生,因为触发器事件是命名空间。我可以使用 custom。* 的效果来监听所有名称空间吗?

In the above example, nothing will happen because the trigger events are namespaced. Can I listen to all namespaces with something to the effect of custom.*?

小提琴演示问题

谢谢

编辑

即使是这样的事情也是可取的,但仍无法让它发挥作用

Even something like this would be desirable but still can't get it to work

$('#test').on('custom.global', log);

$('#test').trigger('custom.global.namespace1');
$('#test').trigger('custom.global.namespace2');

小提琴

推荐答案

尝试 triggerAll 而不是触发器

(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], '/');
});

示例在这个小提琴中

这篇关于绑定到自定义jquery事件的所有命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆