javascriptbackbone.jscoffeescriptbackbone-viewsbackbone-events

Refreshing backbone form (including events) after validation error without reloading page


I have a Backbone view with a form. When the user submits a form there can be a validation error, that is handled by the backend. After I display the error, I want the form to be usable again. I thought I should just do this.delegateEvents(), but for some reason it did not work...

Here is the code:

class App.Views.PlotsCreate extends Backbone.View
  template: JST['plots/create']

    events:
        'submit #new_plot': 'createPlot'


    createPlot: (event) ->
      event.preventDefault()
      @attributes = plot: {name: $('#new_plot_name').val(), docreate: "true", code: code }
      @collection.create @attributes,
        wait: true
        success: (plot) => 
          document.body.style.cursor = 'default'
            @showProgress(plot)
        error: @handleError
      )

    handleError: (entry, response) =>
      if response.status == 422
        errors = $.parseJSON(response.responseText).errors
        for attribute, messages of errors
          $('#new_plot_name').val("#{message}" for message in messages)



    <form class="new_plot" name="create_form" id ="new_plot"  data-remote="true" enctype="multipart/form-data">
      <textarea class="input" id="new_plot_name" name="name" rows="5" maxlength = '140'></textarea> 
      <input class="blue_button btn_generate" name="commit" type="submit" value="create" id ="plot_subm"/>
    </form>   

How do I make the form become functional again (i.e. submit event firing again after the error was displayed)


Solution

  • Failing validation doesn't normally do anything to event bindings; in fact, technically the view doesn't even have a validate method, only models do (and all that method does is trigger an 'error' event and return false). Are you sure you don't have some code on your end that's breaking the view?