Skip to content

Instantly share code, notes, and snippets.

@thurloat
Created January 18, 2012 02:59
Show Gist options
  • Save thurloat/1630584 to your computer and use it in GitHub Desktop.
Save thurloat/1630584 to your computer and use it in GitHub Desktop.
Backbone Form -> Model sync View
# FormView Class
#
# Backbone View subclass that will allow you to bind input fields
# to model fields and keep the data in sync using the same
# declarative syntax you're used to for Backbone Views.
#
# blog post: http://thurloat.com/2012/01/17/backbone-sync-models-and-views
#
# class TestView extends FormView
#
# fieldMap:
# "#phone_number": "phone_number"
# "#first_name, #last_name":
# field: "fullName"
# toModel: "fullNameToModel"
# toForm: "fullNameToForm"
#
# fullNameToModel: ->
# # return the value to set into the model
# "#{@$('#first_name').val()} #{@$('#last_name')}"
#
# fullNameToForm: ->
# nameParts = do @model.get("fullName").split
# @$('#first_name').val nameParts[0]
# @#('#last_name').val nameParts[1]
#
class FormView extends Backbone.View
syncModelToForm: (model, field) ->
for selector, field of @fieldMap
if field.toForm?
do @[field.toForm]
else
@$(selector).val(@model.get field)
syncFormToModel: (jqEvent) ->
setOb = {}
for selector, field of @fieldMap
if field.toModel?
fieldName = field.field
setValue = @[field.toModel] jqEvent
else
fieldName = field
setValue = do @$(selector).val
setOb[fieldName] = setValue
@model.set setOb, (error) -> console.log error
delegateFormSync: (selector, field) ->
$(@el).delegate selector, "change", (ev) =>
@syncFormToModel ev, selector, field
delegateEvents: (events) ->
super
if @model?
@fieldMap = @fieldMap or {}
for selector, field of @fieldMap
# bind selector change to the model
@model.bind "change:#{ field }", @syncModelToForm, @
# bind form element change events to sync up to the model
@delegateFormSync selector, field
@honza
Copy link

honza commented Jan 18, 2012

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment