命名空间自定义事件触发器

时间:2011-01-17 23:04:17

标签: jquery

我对如何在jQuery中使用命名空间自定义事件感到困惑。我从the doc得到的印象是,触发命名空间自定义事件只会触发专门绑定到该事件的处理程序。相反,似乎命名空间几乎被忽略了。以下示例和此处的实时代码:http://jsfiddle.net/kZCBw/1/

    $(document)
        .bind("reset.one", function(){ console.log("reset.one event detected");})
        .bind("reset.two", function(){ console.log("reset.two event detected");})
        .bind("cheese", function(){ console.log("cheese event detected");});

        $("#btn1").click(function(){
            console.log("firing reset.one event");
            $(this).trigger("reset.one");
        });
        $("#btn2").click(function(){
            console.log("firing reset.two event");
            $(this).trigger("reset.two");
        });
        $("#btn3").click(function(){
            console.log("firing reset event");
            $(this).trigger("reset");
        });

        //btn1 click should only trigger handlers bound to "reset.one"
        //and yet it triggers anything starting w/ "reset"

我错过了什么?

提前致谢! -matt

1 个答案:

答案 0 :(得分:11)

我至少可以证实你的例子是一个观察。

如果您使按钮成为监听器(请参阅http://jsfiddle.net/kZCBw/2/),更好地反映文档中的示例代码,它将按预期工作。

但是如果你把它移到DOM树中更高的位置(参见http://jsfiddle.net/kZCBw/3/),它就会失败。

起初,我怀疑这是因为命名空间没有被事件对象冒出来,但我附加了以下代码(http://jsfiddle.net/kZCBw/4/处的实例):

$('*').bind('reset', function(e){
    console.log(e.type + '.' + e.namespace + ' detected at ' + e.currentTarget);
});

正如您所看到的,命名空间正在冒泡。

虽然您正在寻找的行为(名称空间在更高级别的DOM节点上保持有效)未在documentation中明确示例,但我认为这应该是命名空间事件的工作方式。在这种程度上,您现在可以开始寻找“bug或功能”。

在不触及jQuery源代码的情况下完成所需内容的简单方法是在事件处理程序内使用EventObject(我怀疑这是如何在jQuery中首先完成命名空间事件)来过滤事件