Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Form builder plugin for Backbone.js?

Are there any plugins for Backbone.js that do what "form_for" does for Rails? e.g., I provide a model and it provides a DSL for building a form?

like image 511
Farley Knight Avatar asked Jul 27 '11 02:07

Farley Knight


2 Answers

Not familiar with how Rails creates forms but I created a Backbone forms library that may do what you're looking for. You write a simple form schema and it will generate the forms for you:

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

like image 89
evilcelery Avatar answered Nov 05 '22 22:11

evilcelery


I think it is a different beast with a different solution. I wrote a backbone.js extension for binding form elements to Backbone.Model fields. Forgive the coffeescript but I do the following normally.

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) 

The implementation of the binding code is

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

    @

I wrote a small blog article on this here.

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

like image 1
bradgonesurfing Avatar answered Nov 05 '22 23:11

bradgonesurfing