Backbone Forms (Backbone 0.9.1)

Base setup for Backbone Forms

by codeofficer

HTML

<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>
<script src="https://raw.github.com/rails/jquery-ujs/master/src/rails.js"></script>
<p>Be sure to open your console before clicking continue.</p>

<form id="form" action="#" method="POST" data-remote="true">
  <p><input type="text" value="..."></p>
  <p><input type="submit" value="Continue &rarr;"></p>
</form>

JavaScript

var FormView = Backbone.View.extend({
  el: '#form',

  events: {
    // Fired automatically when a file-type input is detected with a
    // non-blank value. You can use this hook to implement a handler that
    // will deal with those non-blank file inputs. Returning false will
    // disallow standard form submission.
    'ajax:aborted:file'     : 'ajaxAbortedFile',

    // Fired when there are required inputs which have been left blank.
    // You can use this handler to deal with those blank required inputs.
    // Returning false will submit the form anyway.
    'ajax:aborted:required' : 'ajaxAbortedRequired',

    // First event fired for any remote enabled form. Stopping this event
    // will cancel the ajax request
    'ajax:before'           : 'ajaxBefore',

    // Fired before the ajax request is sent. Stopping this event will
    // cancel the ajax request. Commonly used to customize certain request
    // headers
    'ajax:beforeSend'       : 'ajaxBeforeSend',

    // Fired after completion, if the HTTP response was a success
    'ajax:success'          : 'ajaxSuccess',

    // Fired after completion, if the server returned an error
    'ajax:error'            : 'ajaxError',

    // Fired after the request has been completed, no matter what outcome
    'ajax:complete'         : 'ajaxComplete'
  },

  ajaxAbortedFile: function(e, elements){
    e.preventDefault();
    console.log('ajaxAbortedFile', e, elements);
  },

  ajaxAbortedRequired: function(e, elements){
    e.preventDefault();
    console.log('ajaxAbortedRequired', e, elements);
  },

  ajaxBefore: function(e){
    e.preventDefault();
    console.log('ajaxBefore', e);
  },

  ajaxBeforeSend: function(e, xhr, settings){
    e.preventDefault();
    console.log('ajaxBeforeSend', e, xhr, settings);
  },

  ajaxSuccess: function(e, data, status, xhr){
    e.preventDefault();
    console.log('ajaxSuccess', e, data);
  },

  ajaxError: function(e, xhr, status, error){
    e.preventDefault();
   ...