Justin Alexander
Justin Alexander

Reputation: 2024

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?

Upvotes: 22

Views: 19348

Answers (4)

Mr. Shiny and New 安宇
Mr. Shiny and New 安宇

Reputation: 13898

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.

Upvotes: 14

Mörre
Mörre

Reputation: 5723

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

Upvotes: 2

Wayne
Wayne

Reputation: 60424

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.

Upvotes: 2

JacobE
JacobE

Reputation: 8141

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
}

Upvotes: 9

Related Questions