停止特定处理程序的事件传播 [英] Stop Event Propagation for a Specific Handler
问题描述
tl; dr总结
编写一个函数,当注册处理层次结构中多个元素上的特定事件时,执行冒泡期间到达的第一个元素,但当进一步向上冒泡时,不会执行(或返回)。 (实际上并没有停止事件的传播。)
简单示例
鉴于这个HTML …
<!DOCTYPE html>
< body>
< div><按钮>点击< /按钮>< / div>
< script>
var d = document.querySelector('div'),
b = document.querySelector('button');
d.addEventListener('mousedown',clickPick,false);
d.addEventListener('mousedown',startDrag,false);
b.addEventListener('mousedown',startDrag,false);
函数clickPick(){console.log('click',this.tagName); }
函数startDrag(){console.log('drag',this.tagName); }
< / script>
…点击该按钮会产生此输出:
拖动BUTTON
点击DIV
拖动DIV
但是,我不想拖动div。具体来说,我希望 startDrag
只能在< button>
中处理一次,它在特定的传播链中注册。
Working解决方案
以下JavaScript代码已在IE9,Chrome18,FF11,Safari5和Opera11上测试到 work 。
function startDrag(evt){
if(seenHandler(evt,startDrag))return ;
console.log('drag',this.tagName);
函数seenHandler(evt,f){
if(!evt.handlers)evt.handlers = [];
for(var i = evt.handlers.length; i--;)if(evt.handlers [i] == f)返回true;
evt.handlers.push(f);
返回false;
}
上面的不是 IE8,即使您使用全局 window.event
对象;相同的事件
对象在冒泡过程中不会被重复使用。
问题
但是,我不确定上述内容是否可以保证可以正常工作,也不会确保它的高雅。
- 在传播过程中是否保证传递相同的
事件
对象 - 是否保证
事件
对象不会再被用于不同的事件派发? -
event
确保支持添加expando属性的对象? - 您能否想到一种更优雅的方式来检测相同的事件处理函数已经在当前的事件派发中看到了?
真实世界应用程序
假设这个SVG层次结构...
< g>
< rect ... />
< rect ... />
< circle ... />
< / g>
...和一个想要的用户可以通过拖动整个组拖动其中的任何矩形,也可以通过拖动它来拖动圆。
现在混入通用拖动库,它为您处理大部分细节。我建议修改这个库,以便如果用户向< g>
和< circle>< / code>然后在圆上拖动会自动阻止在组上开始拖动,但不会停止传播所有
mousedown
事件(因为用户可能会有高这是一个通用的解决方案,适用于所有主流浏览器的当前版本。 ...但不是在IE8中,并且可能不能在以后的版本中使用:
函数seenFunction(evt,f){
var s = evt .__ seenFuncs;
if(!s)s = evt .__ seenFuncs = [];
for(var i = s.length; i--;)if(s [i] === f)返回true;
evt.handlers.push(f);
返回false;
}
//如此使用:
函数myHandler(evt){
if(seenHandler(evt,myHandler))return;
// ...否则,通常运行代码
}
这是一个不那么通用的解决方案,稍微有点但可能不明显更快(再次,不是在IE8中,并且可能未来有保证将来可以使用):
//根据处理程序实现;出现冲突的错误名称很小
函数myHandler(evt){
if(evt .__ ranMyHandler)return;
// ...否则,通常运行代码
evt .__ ranMyHandler = true;
我会很乐意将接受转换为另一个答案, 。
tl;dr Summary
Write a function that—when registered to handle a specific event on multiple elements in a hierarchy—executes on the first element reached during bubbling but does not execute (or returns early) when bubbling further up the hierarchy. (Without actually stopping propagation of the event.)
Simple Example
Given this HTML…
<!DOCTYPE html>
<body>
<div><button>click</button></div>
<script>
var d = document.querySelector('div'),
b = document.querySelector('button');
d.addEventListener('mousedown',clickPick,false);
d.addEventListener('mousedown',startDrag,false);
b.addEventListener('mousedown',startDrag,false);
function clickPick(){ console.log('click',this.tagName); }
function startDrag(){ console.log('drag',this.tagName); }
</script>
…clicking on the button yields this output:
drag BUTTON
click DIV
drag DIV
However, I don't want to drag the div. Specifically, I want startDrag
to only be processed once, on the <button>
, the leaf-most element for which it is registered in a particular propagation chain.
"Working" solution
The following JavaScript code has been tested to work on IE9, Chrome18, FF11, Safari5, and Opera11.
function startDrag(evt){
if (seenHandler(evt,startDrag)) return;
console.log('drag',this.tagName);
}
function seenHandler(evt,f){
if (!evt.handlers) evt.handlers=[];
for (var i=evt.handlers.length;i--;) if (evt.handlers[i]==f) return true;
evt.handlers.push(f);
return false;
}
The above does not work with IE8, even if you use the global window.event
object; the same event
object is not reused during bubbling.
The Question(s)
However, I'm not sure if the above is guaranteed to work…nor if it's as elegant as it could be.
- Is the same
event
object guaranteed to be passed up the chain during propagation? - Is the
event
object guaranteed to never be re-used for different event dispatches? - Is the
event
object guaranteed to support having an expando property added to it? - Can you think of a more elegant way to detect if the same event handler function has been seen already on the current dispatch of an event?
Real World Application
Imagine this SVG hierarchy…
<g>
<rect … />
<rect … />
<circle … />
</g>
…and a user who wants to be able to drag the whole group by dragging on any rect within it, and also to be able to drag just the circle by dragging on it.
Now mix in a generic dragging library that handles most of the details for you. I'm proposing to modify this library such that if the user adds a drag handler to both the <g>
and the <circle>
then dragging on the circle automatically prevents the dragging from initiating on the group, but without stopping propagation of all mousedown
events (since the user might have a high level handler for other purposes that is desirable).
Here's a generic solution that works in the current versions of all major browsers...but not in IE8 and may not be guaranteed to work in future versions:
// Solution supporting arbitrary number of handlers
function seenFunction(evt,f){
var s=evt.__seenFuncs;
if (!s) s=evt.__seenFuncs=[];
for (var i=s.length;i--;) if (s[i]===f) return true;
evt.handlers.push(f);
return false;
}
// Used like so:
function myHandler(evt){
if (seenHandler(evt,myHandler)) return;
// ...otherwise, run code normally
}
Alternatively, here is a less-generic solution that is slightly-but-probably-not-noticeably faster (again, not in IE8 and maybe not guaranteed to work in the future):
// Implemented per handler; small chance of error with a conflicting name
function myHandler(evt){
if (evt.__ranMyHandler) return;
// ...otherwise, run code normally
evt.__ranMyHandler = true;
}
I will happily switch the acceptance to another answer with proper specs provided.
这篇关于停止特定处理程序的事件传播的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!