Created
November 7, 2011 21:12
-
-
Save searls/1346198 to your computer and use it in GitHub Desktop.
A little view that synchronizes a form in the DOM and its backing model via the view object.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class FormView extends Backbone.View | |
events: -> | |
'change :input': 'propogateChangesToModel' | |
render: -> | |
@syncForm(@$('form'),@model) | |
save: (e) -> | |
e.preventDefault() | |
e.stopPropagation() | |
@model.unset("errors") | |
@collection.create @model.toJSON(), | |
success: (createdResource) => | |
@model = createdResource | |
error: (model, jqXHR) => | |
@model.set({errors: $.parseJSON(jqXHR.responseText) }) | |
syncForm: ($form,model)-> | |
self = @ | |
$form.find(':input[name]').each (i,el) -> | |
$el = $(el); | |
name = $el.attr('name') | |
model.bind 'change:'+name, -> $el.val(model.get(name)) | |
if model.get(name) | |
$el.val(model.get(name)) | |
else | |
self.propogateChangesToModel target: el | |
propogateChangesToModel: (e) -> | |
$el = $(e.target) | |
attrs = {} | |
attrs[$el.attr('name')] = $el.val() | |
@model.set attrs |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment