我很难理解命名空间自定义事件应该如何在jQuery中工作.我从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"
Run Code Online (Sandbox Code Playgroud)
我错过了什么?
提前致谢!-matt
Ste*_*ven 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);
});
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,命名空间正在冒泡.
虽然您正在寻找的行为(名称空间在更高级别的DOM节点上保持有效)未在文档中明确示例,但我认为它应该是命名空间事件的工作方式.在这种程度上,您现在可以开始"bug或功能"搜索.
在不触及jQuery源代码的情况下实现所需内容的临时方法是在事件处理程序内使用EventObject(我怀疑这是如何在jQuery中首先完成命名空间事件)来过滤事件.
| 归档时间: |
|
| 查看次数: |
5658 次 |
| 最近记录: |