jQuery:绑定名称空间事件 [英] jQuery: bind namespaces events

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

问题描述

如果事件是名称空间,是否可以监听一个基本事件的所有事件?

Is it possible to listen to ALL events of one basic event if the events are namespaces?

示例:

$elmt.bind("change", function (event) {
    console.log(event);
});
$elmt.trigger("change.namespace1");
$elmt.trigger("change.namespace2");

仅当我绑定完整的事件名称时,此方法才有效,但这是我在此位置不知道的:(

This only works if I bind to the full event names but this is what I don't know on this position :(

推荐答案

尝试用triggerAll代替trigger:

(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天全站免登陆