Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript event handler order

Tags:

javascript

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?

like image 298
Justin Alexander Avatar asked Feb 28 '11 15:02

Justin Alexander


People also ask

In what order are multiple handlers fired?

The vast majority of browser implementations (Chrome, Firefox, Opera, etc.), including IE9, fire the handlers in the order in which they were attached. IE8 and earlier do it the other way around.

In what order does event flow occur after a click '?

That is: for a click on <td> the event first goes through the ancestors chain down to the element (capturing phase), then it reaches the target and triggers there (target phase), and then it goes up (bubbling phase), calling handlers on its way.

How does JavaScript event handler work?

To react to an event, you attach an event handler to it. This is a block of code (usually a JavaScript function that you as a programmer create) that runs when the event fires. When such a block of code is defined to run in response to an event, we say we are registering an event handler.


2 Answers

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.

like image 58
Mr. Shiny and New 安宇 Avatar answered Sep 19 '22 12:09

Mr. Shiny and New 安宇


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
}
like image 25
JacobE Avatar answered Sep 19 '22 12:09

JacobE