2011-07-27 13 views

Odpowiedz

1

Myślę, że to inna bestia z innym rozwiązaniem. Napisałem rozszerzenie backbone.js dla wiążących elementów formularza w polach Backbone.Model. Wybacz coffeescript, ale wykonuję następujące czynności normalnie.

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 """ 
     <form> 
     <input class="address"/> 
     <input class="name"/> 
     <input class="email"/> 
     </form> 
    """ 

    super 

    @ 


# Instantiate the view 
view = new FooView 
    model: new Backbone.Model 

$("body").html(view.el) 

Realizacja kodu wiążącego jest

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 

    @ 

Napisałem mały wpis na blogu na ten temat tutaj.

http://xtargets.com/2011/06/11/binding-model-attributes-to-form-elements-with-backbone-js/

0

pisałem jquery plugin, który pozwala powiązać obiekt json do formularza. Wiem, że to nie jest dokładnie to, czego chciałeś. Myślałem nawet o rozszerzeniu go w celu zbudowania html z definicji obiektu, ale zdecydowałem, że może być trochę trudno stworzyć wtyczkę, która byłaby wystarczająco elastyczna. W każdym razie here to kod z objaśnieniem. Nadal jest w wersji alfa, ale działa. W końcu działa dobrze: D

Możesz także pobrać kod na jquery plugin page

Powiązane problemy