Backbone.Syphon
Easily serialize forms fields in your Backbone.Views into a JSON representation.
About Backbone.Syphon
Backbone.Syphon aims to make it easy to serialize the fields of a Backbone.View into a simple JSON object that contains all of the values.
Working with form fields in a Backbone view can become very tedious very quickly. You will either end up writing a lot of repetitive code to read values from the fields, or end up using a key-value-observer or data-binding solution that automatically populates your model for you. While these are valid options and it is highly recommended to understand how they work, there are times when these options are not the best choice for your application.
Documentation
This readme file contains basic usage examples.
If you need to modify the behaviors of Syphon, see the API document. It contains the documentation for the core APIs that Syphon exposes, with examples on how to change the behaviors of Syphon.
View The API Documentation
Source Code And Downloads
You can download the raw source code from the "src" folder above, or grab one of the builds from the "lib" folder.
To get the latest stable release, use these links which point to the 'master' branch's builds:
Standard Builds
Development: backbone.syphon.js
Production: backbone.syphon.min.js
Basic Usage
Serialize
When the data from a form is needed, you can call the serialize
method of Backbone.Syphon
to retrieve an object
literal that contains the data from your view's form.
BackboneView;
Keys Retrieved By "name" Attribute
The default behavior for serializing fields is to use the field's "name" attribute as the key in the serialized object.
BackboneSyphon; // will produce => a: "" b: "" c: ""
For information on how to change this behavior, see the Key Extractors section of the API Documentation.
.val()
Call
Values Retrieved By jQuery The default behavior for serializing fields is to use jQuery's .val()
to get the value of the input element.
b-value
BackboneSyphon; // will produce => a: "a-value" b: "b-value"
For information on how to change this behavior, see the Input Readers section of the API Documentation.
Checkboxes
By default, a checkbox will return a boolean value signifying whether or not it is checked.
BackboneSyphon; // will produce => a: false b: true c: null
For information on how to change this behavior, see the Input Readers section of the API Documentation.
Radio Button Groups
Radio button groups (grouped by the input element "name" attribute) will produce a single value, from the selected radio button.
BackboneSyphon; // will produce => a: "2"
This behavior can be changed by registering a different set of Key Extractors, Input Readers, and Key Assignment Validators. See the full API Documentation. for more information on these.
Basic Usage : Deserialize
Syphon also allows you to deserialize an object's values back into their field equivalent. It uses the same conventions and configuration as the serialization process, with the introduction of Input Writers to handle populating the fields with the values. See the full API Documentation. for more information on Input Writers.
var data = a: "foo" b: "bar"; BackboneSyphon;
This will populate the form field elements with the correct values from the data
parameter.
Ignored Input Types
The following types of input are ignored, and not included in the resulting JavaScript object:
<input type="submit">
buttons<input type="reset"
> buttons- standard
<button>
tags <fieldset>
tags
If you need to get a value from the specific button that was clicked, you can either include it specifically (see below) or use a DOM event to listen for that element being manipulated (clicked, for example) and manually grab the data you need.
Ignoring Other Input Types
Syphon exposes the list of ignored input types as a raw array. You can push, pop, and manipulate this array as any other array, to specify which types of input fields you want to ignore.
This list is global to Syphon and there is no way to customize it for a specific call to serialize
.
// ignore all <textarea> input elementsBackboneSyphonignoredTypes;
Serializing Nested Attributes And Field Names
Syphon will parse nested attribute names and create a nested result object, using the Rails standard of
name="foo[bar][baz]"
by default.
will produce
foo: bar: "a value" baz: quux: "another value"
Include / Exclude Specific Fields
You can include or exclude specific fields as needed. Inclusion is given priority and specifying fields to include will force Syphon to exclude all other fields. Including a field that is ignore by it's type will also force the field to be included.
Examples
Given this HTML:
The following will occur:
// include a, b onlyBackboneSyphon; // will produce => a: "a-value" b: "b-value"
// include the normally excluded (button) "d"BackboneSyphon; // will produce => a: "a-value" d: "d-value"
// exclude aBackboneSyphon; // will produce => b: "b-value" c: "c-value"
// include a and b, exclude b and cBackboneSyphon; // will produce => a: "a-value" b: "b-value"
Include / Exclude Based On Key Extractors
The include / exclude process uses the registered Key Extractors to determine which fields to include / exclude.
This means if you are only using the default Key Extractor which uses the "name" attribute, all fields will be included or excluded based on the name of the field.
If you have registered other Key Extractors, they will be used when determining which fields to include / exclude.
// By default, use the "id"BackboneSyphonKeyExtractors; // For radio buttons, use the "name"BackboneSyphonKeyExtractors; // Serialize the formBackboneSyphon; // This will produce => c: "" d: ""
For more information on Key Extractors, see the full API Documentation.
Other Options
There are a few other options that can be specified when calling the Syphon.serialize
method, which allow the
behavior of Syphon to be altered for a single call instead of for all calls.
Key Extractors
Key extractors are used to generate the "key" in the {key: "value"}
result. You can specify a KeyExtractorSet
as part of the options:
extractors = ;// configure it ... BackboneSyphon;
For more information on Key Extractors, see the full API Documentation.
Input Readers
Input Readers are used to generate the "value" in the {key: "value"}
result. You can specify a InputReadetSet
as part of the options:
readers = ;// configure it ... BackboneSyphon;
For more information on Input Readers, see the full API Documentation.
Input Writers
Input Writers are used to set the value of form fields to the "value" in the {key: "value"}
data / object.
At this time, you cannot specify input writers in the deserialize
method. That will come soon, hopefully.
For more information on Input Writers, see the full API Documentation.
Key Assignment Validators
Input Readers are used to validate the assignment of a key to a value, in the context of an element. You can specify
a InputReadetSet
as part of the options:
validators = ;// configure it ... BackboneSyphon;
For more information on Key Assignment Validators, see the full API Documentation.
Current Limitations
There some known limitations in Backbone.Syphon, partially by design and partially implemented as default behaviors.
- An input of type
checkbox
will return a boolean value. This can be overriden by replacing the Input Reader for checkboxes. - To avoid circular references, care should be taken when using Backbone.Relational. See (#33)[https://github.com/marionettejs/backbone.syphon/issues/33].
contenteditable
fields will only be processed if they are explicitly assigned thetrue
value:contenteditable="true"
.
Building Backbone.Syphon
If you wish to build Backbone.Syphon on your system, you will need NodeJS and grunt to run the build.
Testing Backbone.Syphon
There are two methods to running the unit test suite, suited for your desired workflow and overall developer happiness:
you can open SpecRunner.html in the browser or run npm test
To begin ensure that you have installed the project dev dependencies via:
$ npm install
In a browser
Open SpecRunner.html in your browser.
Via Grunt
Running grunt
alone will default to running the tests once.
Via npm
$ npm test
To Build The Packages
-
Be sure you have NodeJS and NPM installed on your system
-
Run
npm install -g grunt
to install the grunt build system -
From the project folder, run
grunt build
to produce a build
Screencasts
I've recorded several screencasts on how I built Syphon.
- WatchMeCode: Episode 7: covers the initial project setup, build and release
- WatchMeCode: Episode 8: covers setting up an AMD build along side the standard build
Release Notes
See the changelog.md file.
Legal Mumbo Jumbo (MIT License)
Copyright (c) 2012 Derick Bailey, Muted Solutions, LLC
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.