【发布时间】:2018-06-29 15:21:08
【问题描述】:
使用此代码时:
document.addEventListener("keydown", function(e) {
if (e.keyCode == 9)
{
storage.get("items", function(obj) { // this is an asynchronous call
if (some_condition(obj)) {
e.preventDefault();
e.stopPropagation();
}
});
}
}
如果some_condition(取决于异步调用的结果)为True,则e.preventDefault();和e.stopPropagation();将被执行为时已晚,因为storage.get是异步的。
什么选项可以决定在异步调用的结果之后是否应该调用 preventDefault()?
我正在考虑这个解决方案:
document.addEventListener("keydown", function(e) {
if (e.keyCode == 9)
{
e.preventDefault(); // always preventDefault and stopPropogation,
e.stopPropagation(); // we'll maybe restore it later
storage.get("items", function(obj) { // this is an asynchronous call
if (!some_condition) {
e.reenableDefault(); // contrary of preventDefault
e.restartPropagation(); // contrary of stopPropagation
}
});
}
}
但显然没有e.restartPropagation();函数!
注意:我已经阅读了How to reenable event.preventDefault?,但这在这种情况下没有帮助。
【问题讨论】:
-
如有必要,只需触发一个新事件(假设您无法直接调用该事件应该实现的目标,但您的应用程序似乎在那里设计得不好)。
-
您可以在适当的时间间隔独立于用户输入来轮询异步函数,并将其存储在可同步访问的上下文中,以便同步检查事件处理程序中的条件。
-
您想要做的实际上是不可能的。你需要重新考虑你想要做什么。
-
@DenysSéguret 如何重新触发一个“看起来像”在 textarea / contenteditable 中触发的普通 TAB 按键的“TAB”按键?
-
@PatrickRoberts 我正在考虑这个问题:独立进行异步调用并将结果填充到变量中(可从按键事件监听器访问),但这需要频繁(每 5 秒)调用这个异步函数或受到非最新更新的内容的影响......它看起来像是一个非最佳解决方案。有什么想法吗?
标签: javascript asynchronous preventdefault event-bubbling