Can I bind form inputs to models in Backbone.js without manually tracking blur events?

后端 未结 6 1551
抹茶落季
抹茶落季 2021-01-29 18:32

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

6条回答
  •  自闭症患者
    2021-01-29 19:03

    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 :)

提交回复
热议问题