Form builder plugin for Backbone.js?



是否有任何插件为Backbone.js做什么"form_for"做Rails?例如,我提供了一个模型,它提供了一个构建表单的DSL ?

不熟悉Rails如何创建表单,但我创建了一个骨干表单库,可以做你正在寻找的。您编写一个简单的表单模式,它将为您生成表单:

https://github.com/powmedia/backbone-forms

我认为这是一个有不同解决方案的不同的野兽。我编写了一个Backbone. js扩展,用于将表单元素绑定到Backbone。领域模型。请原谅我的咖啡脚本,但我通常会这样做。

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) 

绑定代码的实现为

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
    @

我在这里写了一篇关于这个的小博客文章。

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

我编写了一个jquery插件,允许您将json对象绑定到表单。我知道这不是你想要的。我甚至想把它扩展到从对象定义开始构建html,但我认为创建足够灵活的插件可能有点困难。无论如何,这里是一些解释的代码。它还在alpha版本,但它可以工作。D

你也可以抓取jquery插件页面上的代码

最新更新