javascript - javascript 在异步计算后决定调用 stopPropagation
问题描述
HTML 元素有一个容器组件结构。容器元素有一个click
附加到它的处理程序。这个处理程序的操作对于大多数内容来说已经足够好了。但是一些组件有自己的click
处理程序和更具体的条件行为。在某些情况下,事件不应传播到组件之外,也就是说,容器被阻止对此类click
事件做出反应。
阻止事件同步冒泡很容易。
是否可以将决定推迟到完成一些长时间的异步计算?
component.addEventListener(
"click",
(e)=>{
// this is OK, but conditions are not known yet
if(flag) {
e.stopPropagation();
}
setTimeout(
()=>compute(),
1500,
);
},
)
是否可以在计算完成后推迟决定是否停止事件传播。
(e)=>{
setTimeout(
()=>{
flag = compute(),
if(flag) {
// this will not work as expected
e.stopPropagation();
}
},
1500,
);
}
在组件的父元素或 event.target.parentElement 上使用 HTMLElement::click() 的推荐解决方案是什么?
(e)=>{
e.stopPropagation();
setTimeout(
()=>{
const flag = compute();
if(!flag){
component.parentElement.click();
// e.target.parentElement.click();
}
},
1500,
);
}
有更好的方法吗?