Javascript event handler order

后端 未结 4 1422
我在风中等你
我在风中等你 2020-12-03 14:37

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

相关标签:
4条回答
  • 2020-12-03 15:04

    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
    }
    
    0 讨论(0)
  • 2020-12-03 15:04

    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.

    0 讨论(0)
  • 2020-12-03 15:04

    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

    0 讨论(0)
  • 2020-12-03 15:11

    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.

    0 讨论(0)
提交回复
热议问题