I have a backbone.js app (www.github.com/juggy/job-board) where I want to bind my form inputs directly to my model (a la Sproutcore).
Is it possible with Backbone.js (or
I created the following technique on my site
class FooView extends MyView
tag: "div"
modelBindings:
"change form input.address" : "address"
"change form input.name" : "name"
"change form input.email" : "email"
render: ->
$(@el).html """
"""
super
@
# Instantiate the view
view = new FooView
model: new Backbone.Model
$("body").html(view.el)
I've detailed the extensions to backbone you need to make on my blog
http://xtargets.com/2011/06/11/binding-model-attributes-to-form-elements-with-backbone-js/
it uses the same declarative style as the events property for binding form elements to model attributes
and here is the actual code implementing the class for you in coffeescript
class MyView extends Backbone.View
render: ->
if @model != null
# Iterate through all bindings
for selector, field of @modelBindings
do (selector, field) =>
console.log "binding #{selector} to #{field}"
# When the model changes update the form
# elements
@model.bind "change:#{field}", (model, val)=>
console.log "model[#{field}] => #{selector}"
@$(selector).val(val)
# When the form changes update the model
[event, selector...] = selector.split(" ")
selector = selector.join(" ")
@$(selector).bind event, (ev)=>
console.log "form[#{selector}] => #{field}"
data = {}
data[field] = @$(ev.target).val()
@model.set data
# Set the initial value of the form
# elements
@$(selector).val(@model.get(field))
super
@
Appologies if you don't like coffeescript. I do. Everybody is different :)