I'm stumped on how namespaced custom events are supposed to work in jQuery. I got the impression from the doc that triggering a namespaced custom event will only fire handlers specifically bound to that event. Instead, it seems the namespace is pretty much ignored. Example below and live code here: 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"我想念什么?提前谢谢!-哑光推荐答案我至少可以证实您的示例并添加一个观察结果.I can at least corroborate your example an add an observation.如果将按钮设为侦听器(请参见 http://jsfiddle.net/kZCBw/2/),可以更好地在文档中反映示例代码,它可以按预期工作.If you make the button the listener (see http://jsfiddle.net/kZCBw/2/), better reflecting the sample code in the documentation, it works as expected.但是,如果将其移动到DOM树中的更高位置(请参见 http://jsfiddle.net/kZCBw/3/),则失败.But if you move it anywhere higher up in the DOM tree (see http://jsfiddle.net/kZCBw/3/), it fails.起初,我怀疑这是因为名称空间没有被事件对象冒泡,但是我附加了以下代码(在 http://jsfiddle.net/kZCBw/4/):At first, I suspected that this was because the namespace wasn't being bubbled up with the event object, but I appended the following code (live example at http://jsfiddle.net/kZCBw/4/):$('*').bind('reset', function(e){ console.log(e.type + '.' + e.namespace + ' detected at ' + e.currentTarget);});如您所见,名称空间正在冒泡.As you can see, the namespace is being bubbled up just fine. 文档,我认为这应该是命名空间事件的工作方式.在这种程度上,您现在可以开始"bug或功能"搜寻.While the behaviour you're looking for (namespace remaining effective at higher level DOM nodes) is not explicitly exemplified in the documentation, I feel that it should be the way namespaced events work. To this extent, you can now begin the "bug or feature" hunt.在不触摸jQuery源代码的情况下完成您要查找的内容的一种临时方法是仅使用事件处理程序中的EventObject(我怀疑这是首先在jQuery中完成命名空间事件的方式)过滤事件A makeshift way to accomplish what you're looking for without touching the jQuery source code is to just filter the event using the EventObject (I suspect this is how namespaced events are accomplished in jQuery in the first place) inside the event handler. 这篇关于命名空间的自定义事件触发器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
05-29 00:23
查看更多