Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Serialize a Backbone.View in to a JavaScript object

NotificationsYou must be signed in to change notification settings

4amitnarayan/backbone.syphon

 
 

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.

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 linkswhich point to the 'master' branch's builds:

Standard Builds

Development:backbone.syphon.js

Production:backbone.syphon.min.js

AMD/RequireJS Builds

Development:backbone.syphon.js

Production:backbone.syphon.min.js

Documentation

This readme file contains basic usage examples.

Extensibility / API Documentation

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.

Annotated Source Code

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.

Basic Usage : Serialize

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}});

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.

<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.

Values Retrieved By jQuery.val() Call

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.

Checkboxes

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

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.

Basic Usage : Deserialize

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.

Ignored Input Types

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.

Ignoring Other Input Types

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");

Serializing Nested Attributes And Field Names

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"}}}

Include / Exclude Specific Fields

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.

Examples

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"}

Include / Exclude Based On Key Extractors

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.

Other Options

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

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

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

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.

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 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.

Current Limitations

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 typecheckbox will return a boolean value. This can beoverriden by replacing the Input Reader for checkboxes.

Building Backbone.Syphon

If you wish to build Backbone.Syphon on your system, you willneed Ruby to run the Jasmine specs, and NodeJS to run thegrunt build.

To Run The Jasmine Specs

  1. Be sure you have Bundler installed in your Ruby Gems. Thenrunbundle install from the project folder

  2. Once this is done, you can runrake jasmine to run theJasmine server

  3. Point your browser athttp://localhost:8888 and you willsee all of the specs for Backbone.Syphon

To Build The Packages

  1. Be sure you have NodeJS and NPM installed on your system

  2. Runnpm install -g grunt to install the grunt build system

  3. From the project folder, rungrunt to produce a build

Screencasts

I've recorded several screencasts on how I built Syphon.

Release Notes

See the [changelog.md]((https://github.com/derickbailey/backbone.syphon/blob/master/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.

About

Serialize a Backbone.View in to a JavaScript object

Resources

Stars

Watchers

Forks

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp