- Notifications
You must be signed in to change notification settings - Fork0
4amitnarayan/backbone.syphon
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Backbone.Syphon - serialize the forms in yourBackbone.Views into a JSON object for use withBackbone's models.
Working with form elements in a Backbone view can becomevery tedious very quickly. You will either end up writinga lot of repetitive code to read values from the form,or end up using a key-value-observer or data-bindingsolution that automatically populates your model for you.While these are valid options and I highly recommendunderstanding how they work, there are times when theseoptions are not the best choice for your application.
Backbone.Syphon aims to make it easy to serialize theform inputs of a Backbone.View in to a simple JSON objectthat contains all of the values from the form.
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 linkswhich point to the 'master' branch's builds:
Development:backbone.syphon.js
Production:backbone.syphon.min.js
Development:backbone.syphon.js
Production:backbone.syphon.min.js
This readme file contains basic usage examples.
If you need to modify the behaviors of Syphon, see the API document. Itcontains the documentation for the core APIs that Syphon exposes, withexamples on how to change the behaviors of Syphon.
Syphon has annotated source code using the Docco tool to turncomments in to documentation. This provides an in-depth lookat what each section of is doing.
When the data from a form is needed, you can call theserialize
method ofBackbone.Syphon
to retrieve anobject literal that contains the data from your view'sform.
Backbone.View.extend({events:{"submit form":"formSubmitted"},formSubmitted:function(e){e.preventDefault();vardata=Backbone.Syphon.serialize(this);this.model.set(data);this.model.save();},render:function(){// build the view's form, here}});
The default behavior for serializing fields is to use the field's "name"attribute as the key in the serialized object.
<form><inputname="a"><selectname="b"></select><textareaname="c"></textarea></form>
Backbone.Syphon.serialize(view);// will produce =>{a:"",b:"",c:""}
For information on how to change this behavior, see the Key Extractorssection of theAPI Documentation.
The default behavior for serializing fields is to use jQuery's.val()
to get the value of the input element.
<form><inputname="a"value="a-value"><textareaname="b">b-value</textarea></form>
Backbone.Syphon.serialize(view);// will produce =>{a:"a-value",b:"b-value",}
For information on how to change this behavior, see the Input Readerssection of theAPI Documentation.
By default, a checkbox will return a boolean value signifying whether ornot it is checked.
<form><inputtype="checkbox"name="a"><inputtype="checkbox"name="b"checked></form>
Backbone.Syphon.serialize(view);// will produce =>{a:false,b:true}
For information on how to change this behavior, see the Input Readerssection of theAPI Documentation.
Radio button groups (grouped by the input element "name" attribute) willproduce a single value, from the selected radio button.
<form><inputtype="radio"name="a"value="1"><inputtype="radio"name="a"value="2"checked><inputtype="radio"name="a"value="3"><inputtype="radio"name="a"value="4"></form>
Backbone.Syphon.serialize(view);// will produce =>{a:"2"}
This behavior can be changed by registering a different set of KeyExtractors, Input Readers, and Key Assignment Validators. See the fullAPI Documentation.for more information on these.
Syphon also allows you to deserialize an object's values back on to aform. It uses the same conventions and configuration as the serializationprocess, with the introduction of Input Writers to handle populating theform fields with the values. See the fullAPI Documentation.for more information on Input Writers.
<form><inputtype="text"name="a"><inputtype="text"name="b"></form>
vardata={a:"foo",b:"bar"};Backbone.Syphon.deserialize(this,data);
This will populate the form input elements with the correct values fromthedata
parameter.
The following types of input are ignored, and not included inthe 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 wasclicked, you can either include it specifically (see below) or usea DOM event to listen for that element being manipulated (clicked, forexample) and manually grab the data you need.
Syphon exposes the list of ignored input types as a raw array. You canpush, pop, and manipulate this array as any other array, to specify whichtypes of input fields you want to ignore.
This list is global to Syphon and there is no way to customize it fora specific call toserialize
.
// ignore all <textarea> input elementsBackbone.Syphon.ignoredTypes.push("textarea");
Syphon will parse nested attribute names and create a nested result object,using the Rails standard ofname="foo[bar][baz]"
by default.
<form><inputtype="text"name="foo[bar]"value="a value"><inputtype="text"name="foo[baz][quux]"value="another value"></form>
will produce
{foo:{bar:"a value",baz:{quux:"another value"}}}
You can include or exclude specific fields as needed. Inclusion is givenpriority and specifying fields to include will force Syphon to exclude allother fields. Including a field that is ignore by it's type will also forcethe field to be included.
Given this HTML:
<form><inputname="a"value="a-value"><inputname="b"value="b-value"><inputname="c"value="c-value"><buttonname="d"value="d-value"></form>
The following will occur:
// include a, b onlyBackbone.Syphon.serialize(view,{include:["a","b"]});// will produce =>{a:"a-value",b:"b-value"}
// include the normally excluded (button) "d"Backbone.Syphon.serialize(view,{include:["a","d"]});// will produce =>{a:"a-value",d:"d-value"}
// exclude aBackbone.Syphon.serialize(view,{exclude:["a"]});// will produce =>{b:"b-value",c:"c-value"}
// include a and b, exclude b and cBackbone.Syphon.serialize(view,{include:["a","b"],exclude:["b","c"]});// will produce =>{a:"a-value",b:"b-value"}
The include / exclude process uses the registered Key Extractors to determinewhich fields to include / exclude.
This means if you are only using the default Key Extractor which usesthe "name" attribute, all fields will be included or excluded based onthe name of the field.
If you have registered other Key Extractors, they will be used whendetermining which fields to include / exclude.
<form><inputid="a"><inputtype="radio"name="b"><inputid="c"><inputtype="radio"name="d"></form>
// By default, use the "id"Backbone.Syphon.KeyExtractors.registerDefault(function($el){return$el.prop("id");});// For radio buttons, use the "name"Backbone.Syphon.KeyExtractors.register("radio",function($el){return$el.prop("name");});// Serialize the formBackbone.Syphon.serialize(view,{exclude:["a","b"]});// This will produce =>{c:"",d:""}
For more information on Key Extractors, see the fullAPI Documentation.
There are a few other options that can be specified when calling theSyphon.serialize
method, which allow the behavior of Syphon to bealtered for a single call instead of for all calls.
Key extractors are used to generate the "key" in the{key: "value"}
result. You can specify aKeyExtractorSet
as part of the options:
extractors=newBackbone.Syphon.KeyExtractorSet();// configure it ...Backbone.Syphon.serialize({keyExtractors:extractors});
For more information on Key Extractors, see the fullAPI Documentation.
Input Readers are used to generate the "value" in the{key: "value"}
result. You can specify aInputReadetSet
as part of the options:
readers=newBackbone.Syphon.InputReaderSet();// configure it ...Backbone.Syphon.serialize({inputReaders:readers});
For more information on Input Readers, see the fullAPI Documentation.
Input Writers are used to set the value of form elements to the"value" in the{key: "value"}
data / object. At this time, you cannotspecify input writers in thedeserialize
method. That will comesoon, hopefully.
For more information on Input Writers, see the fullAPI Documentation.
Input Readers are used to validate the assignment of a key to a value,in the context of an element. You can specify aInputReadetSet
as partof the options:
validators=newBackbone.Syphon.KeyAssignmentValidators();// configure it ...Backbone.Syphon.serialize({keyAssignmentValidators:validators});
For more information on Key Assignment Validators, see the fullAPI Documentation.
There some known limitations in Backbone.Syphon, partially by design andpartially implemented as default behaivors.
- You must have a
<form>
within your view's$el
- An input of type
checkbox
will return a boolean value. This can beoverriden by replacing the Input Reader for checkboxes.
If you wish to build Backbone.Syphon on your system, you willneed Ruby to run the Jasmine specs, and NodeJS to run thegrunt build.
Be sure you have Bundler installed in your Ruby Gems. Thenrun
bundle install
from the project folderOnce this is done, you can run
rake jasmine
to run theJasmine serverPoint your browser at
http://localhost:8888
and you willsee all of the specs for Backbone.Syphon
Be sure you have NodeJS and NPM installed on your system
Run
npm install -g grunt
to install the grunt build systemFrom the project folder, run
grunt
to produce a build
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
See the [changelog.md]((https://github.com/derickbailey/backbone.syphon/blob/master/changelog.md) file.
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.
About
Serialize a Backbone.View in to a JavaScript object
Resources
Uh oh!
There was an error while loading.Please reload this page.