简体   繁体   中英

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?

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.

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.

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

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

  // do the save
}

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

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. 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. See http://www.quirksmode.org/js/events_order.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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