jQuery   发布时间:2022-03-30  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了绑定到自定义jquery事件的所有命名空间大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试监听自定义事件,但我希望有效地“忽略”它是命名空间或以某种方式监听所有命名空间而不单独定义它们的事实. @H_673_5@ @H_673_5@
$('#test').on('custom',...);

$('#test').trigger('custom.namespace1');
$('#test').trigger('custom.namespace2');
@H_673_5@我希望能够做到这一点的原因是因我有多个ui插件可以在隐藏/显示事件时触发事件.这些事件主要在内部使用,但是命名空间,因此它们不会相互冲突.但是,我还想知道何时隐藏特定的ui元素,而不依赖于其执行其他清理逻辑的源.

@H_673_5@在上面的示例中,由于触发器事件是命名空间,因此不会发生任何事情.我可以使用自定义效果来监听所有名称空间.*?

@H_673_5@Fiddle demonstrating the problem.

@H_673_5@谢谢

@H_673_5@编辑

@H_673_5@即便是类似的东西也是可取的,但仍然无法让它发挥作用

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

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

解决方法

尝试使用triggerAll而不是触发器: @H_673_5@ @H_673_5@
(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,t) {
                $this.trigger(t,data);
            });
        });
    };
})(jQuery);
@H_673_5@当然,由于jQuery处理触发命名空间的方式,触发“root”事件实际上会触发命名空间版本,因此为了得到你期望的,你需要使用另一个字符作为分隔符,比如/,然后声明你的事件,如:

@H_673_5@
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],'/');
});
@H_673_5@例in this fiddle

大佬总结

以上是大佬教程为你收集整理的绑定到自定义jquery事件的所有命名空间全部内容,希望文章能够帮你解决绑定到自定义jquery事件的所有命名空间所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。