简体   繁体   English

Javascript事件处理程序命令

[英]Javascript event handler order

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? 这很好用,但有没有办法保证在所有情况下自动保存之前运行Validate?

If you use JQuery to bind your events, it guarantees that handlers are fired in the same order that they were bound. 如果使用JQuery来绑定事件,则可以保证处理程序的触发顺序与它们绑定的顺序相同。 Otherwise the order is officially undefined. 否则订单正式未定义。

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或类似的框架,你可以通过使用自己的自定义偶数绑定轻松地模拟它,其中你的泛型处理程序是一个函数,它保存一系列函数并按顺序调用它们。

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
}

Why not attach just one handler -- Validate -- and call AutoSave from inside it? 为什么不只附加一个处理程序 - Validate - 并从里面调用AutoSave

For an answer to your question that isn't also a question, see this post or this one or this one . 对于您的问题的答案,这也不是一个问题,请参阅这篇文章这一篇这一篇

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. 它可以在任何给定的实现中是可预测的,但是这可以从一个(Javascript)实现改变到下一个和/或随着时间的推移。 The only thing certain is that they all will be executed - but not in what order. 唯一确定的是,它们都将被执行 - 但不是以什么顺序执行。

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. 请注意,当有一个DOM对象的事件处理程序和另一个用于子对象或父对象的同一事件时,情况类似 - 首先执行哪些事件并不总是很清楚。 See http://www.quirksmode.org/js/events_order.html 请参阅http://www.quirksmode.org/js/events_order.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM