Javascript 事件处理程序顺序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5143817/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 16:08:41  来源:igfitidea点击:

Javascript event handler order

javascript

提问by Justin Alexander

I have an input field, which has two event handlers bound to it.

我有一个输入字段,它绑定了两个事件处理程序。

Validate & AutoSave

验证和自动保存

Obviously I want to validate before I save. If validation fails, the "invalid" class is added to the input and autosave will check for that class before it proceeds.

显然我想在保存之前进行验证。如果验证失败,“无效”类将添加到输入中,自动保存将在继续之前检查该类。

This works well enough, but is there a way to guarantee Validate runs before Autosave in all cases?

这工作得很好,但是有没有办法保证在所有情况下在自动保存之前验证运行?

采纳答案by u7867

If you use JQuery to bind your events, it guarantees that handlers are fired in the same order that they were bound. Otherwise the order is officially undefined.

如果您使用 JQuery 来绑定您的事件,它可以保证处理程序的触发顺序与它们绑定的顺序相同。否则,该顺序是官方未定义的。

If you cannot use JQuery or a similar framework you can easily simulate this by using your own custom even binding, where your generic handler is a function which keeps an array of functions and calls them in order.

如果您不能使用 JQuery 或类似的框架,您可以使用您自己的自定义偶数绑定轻松地模拟这一点,其中您的通用处理程序是一个函数,它保留一组函数并按顺序调用它们。

回答by JacobE

Normally you'd have the Save event handler call Validate() which will return true if everything is fine and ready to be saved.

通常情况下,您会使用 Save 事件处理程序调用 Validate(),如果一切正常并准备好保存,它将返回 true。

function onSaved() {
  if (!validate()) {
    // set class
    return;
  }

  // do the save
}

回答by Wayne

Why not attach just one handler -- Validate-- and call AutoSavefrom inside it?

为什么不只附加一个处理程序 -- Validate-- 并AutoSave从它内部调用?

For an answer to your question that isn't also a question, see this postor this oneor this one.

对于一个回答你的问题,是不是也有问题,看到这个帖子还是这一个这一个

回答by M?rre

Already answered - but just to add this piece of knowledge, the order of event handlers can not be relied upon. It may in any given implementation be predictable, but this can change from one (Javascript) implementation to the next and/or over time. The only thing certain is that they all will be executed - but not in what order.

已经回答 - 但只是为了添加这一知识,不能依赖事件处理程序的顺序。它可能在任何给定的实现中都是可预测的,但这可以从一个 (Javascript) 实现更改为下一个和/或随着时间的推移。唯一可以确定的是,它们都将被执行——但不是按什么顺序执行。

Note that the situation is similar when there is an event handler for a DOM object and another one for the same event for a child or parent - which of those is executed first is not always clear as well. See http://www.quirksmode.org/js/events_order.html

请注意,当有一个用于 DOM 对象的事件处理程序和另一个用于子级或父级的相同事件的事件处理程序时,情况是相似的——其中哪一个先执行并不总是很清楚。见http://www.quirksmode.org/js/events_order.html