FormDelegate, Creates a Clear Path to Elegant Form Hijaxing

FormDelegate creates a layer between a Backbone Model and an HTML Form. Creating a smooth workflow for hijaxing a form's submit event and normalizing the form data to be consumed by a model.

Here is our example form, it's very simple, 3 elements, 2 text boxes.

<div id="form-container"> <form action="somewhere.api" method="POST"> <input type="text" name="name" /> <input type="text" name="occupation" /> <input type="submit" value="Submit" /> </form> </div>
Delegate to Model

An example of binding a FormDelegate's submit event to a Backbone Model. FormDelegate does the heavy lifting of extracting the values from each of the form's elements and assigning that structure to the data property of the submit event.

var form = new Traffic.FormDelegate("#form-container"); var model = new Backbone.Model(); form.on("submit", handleSubmit); function handleSubmit(evt){ model.set("name",; model.set("occupation", }
Delegate to Request

With an HttpRequest in front to achieve pessimistic model creation and only creation, with the request set to POST, it will continue to send POST requests.

var form = new Traffic.FormDelegate("#form-container"); var model = new Backbone.Model(); var request = new Traffic.HttpRequest("/somewhere.api", "POST"); request.on("success", handleSuccess); form.on("submit", handleSubmit); function handleSuccess(response){ model.set(response); } function handleSubmit(evt){ request.send(; }
Delegate to Model with a BackboneRequest

Use the BackboneRequest class to manage the HTTP Verb for you based off of the Backbone CRUD vocabulary. This also puts the request behind the model, this is an optimistic approach to saving information.

var form = new Traffic.FormDelegate("#form-container"); var request = new Traffic.BackboneRequest("/somewhere.api"); var model = new Backbone.Model({}, { request : request }); form.on("submit", handleSubmit); function handleSubmit(evt){ model.set(; }
Model Data to Form

FormDelegate also handles the task of populating a form with a Model.

var form = new Traffic.FormDelegate("#form-container"); var model = new Backbone.Model({ name : "Fred", occupation : "Butler" }); form.applyModel(model);

External Resources