我可以将表单输入绑定到 Backbone.js 中的模型而不手动跟踪模糊事件吗?

发布于 2024-09-30 09:09:24 字数 252 浏览 4 评论 0原文

我有一个backbone.js应用程序(www.github.com/juggy/job-board ),我想将表单输入直接绑定到我的模型(la Sproutcore)。

是否可以使用 Backbone.js(或其他工具)而不实际跟踪输入上的每个模糊事件并手动更新模型?这看起来像是很多粘合代码。

谢谢,
朱利安

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 other tools) without actually tracking each blur events on the inputs and updating the model manually? This seems like a lot of glue code.

Thanks,
Julien

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

美男兮 2024-10-07 09:09:24

如果您的模型包含大量属性,则有一种更好的方法来处理此问题。

SampleView = Backbone.View.extend({
    el: "#formEl",

    events: {
        "change input": "changed",
        "change select": "changed"
    },

    initialize: function () {
        _.bindAll(this, "changed");
    },

    changed:function (evt) {
       var changed = evt.currentTarget;
       var value = $(evt.currentTarget).val();
       var obj = {};
       obj[changed.id] = value;
       this.model.set(obj);
    }
 });

依赖于您的输入元素的 id 与模型中属性的名称相同。

There is an even nicer way to handle this if your model includes lots of properties in it.

SampleView = Backbone.View.extend({
    el: "#formEl",

    events: {
        "change input": "changed",
        "change select": "changed"
    },

    initialize: function () {
        _.bindAll(this, "changed");
    },

    changed:function (evt) {
       var changed = evt.currentTarget;
       var value = $(evt.currentTarget).val();
       var obj = {};
       obj[changed.id] = value;
       this.model.set(obj);
    }
 });

There is a reliance on your input elements having an id the same as the what the name of the property in your model is.

单调的奢华 2024-10-07 09:09:24

我不确定 SC 是如何做到的,但可能他们也监听事件。

window.SomeView = Backbone.View.extend({
  events: {
    "change input.content":  "contentChanged"
  },
  initialize: function() {
    _.bindAll(this, 'contentChanged');
    this.inputContent = this.$('input.content');
  },
  contentChanged: function(e) {
    var input = this.inputContent;

    // if you use local storage save 
    this.model.save({content: input.val()});

    // if you send request to server is prob. good idea to set the var and save at the end, in a blur event or in some sync. maintenance timer.
    // this.model.set({content: input.val()});
  }
});

I'm not sure how SC does it but probably they listen for events too.

window.SomeView = Backbone.View.extend({
  events: {
    "change input.content":  "contentChanged"
  },
  initialize: function() {
    _.bindAll(this, 'contentChanged');
    this.inputContent = this.$('input.content');
  },
  contentChanged: function(e) {
    var input = this.inputContent;

    // if you use local storage save 
    this.model.save({content: input.val()});

    // if you send request to server is prob. good idea to set the var and save at the end, in a blur event or in some sync. maintenance timer.
    // this.model.set({content: input.val()});
  }
});
北音执念 2024-10-07 09:09:24

我认为这是一种从输入元素创建对象

changed: function(evt) {
  var target = $(evt.currentTarget),
      data = {};
  data[target.attr('name')] = target.val();
  this.model.set(data);
},

而不使用 jquery 的更干净(也许更快)的方法:

changed: function(evt) {
  var target = evt.currentTarget,
      data = {};
  data[target.name] = target.value;
  this.model.set(data);
},

I think this is a cleaner (and maybe faster) way to create an object from an input element

changed: function(evt) {
  var target = $(evt.currentTarget),
      data = {};
  data[target.attr('name')] = target.val();
  this.model.set(data);
},

without jquery:

changed: function(evt) {
  var target = evt.currentTarget,
      data = {};
  data[target.name] = target.value;
  this.model.set(data);
},
乖乖公主 2024-10-07 09:09:24

你尝试过Backbone.ModelBinder吗?这是一个很好的工具,可以满足您的需要:https://github.com/theironcook/Backbone.ModelBinder< /a>

Have you tried Backbone.ModelBinder? It´s a nice tool to do what you need: https://github.com/theironcook/Backbone.ModelBinder

叫嚣ゝ 2024-10-07 09:09:24

我正在开发 corset,这是一个受 django forms 模块启发的backbone.js 表单库,但范围不太宏大。仍在解决问题,但至少在半稳定且功能正常时,它最终会出现在 github 上。

Corset 的目的是轻松地对字段类进行子类化,以便您可以为更复杂的用例(级联选择等)构建复杂的输入。这种方法将每个字段渲染为单独的视图,并且表单视图绑定到模型并使用更改事件、模糊事件或提交事件来更新模型(可配置,默认为模糊)。每个视图都有一个可重写的 getData 函数,默认情况下映射到 jquery .val() 函数。

使用合理的默认值和 modelFormFactory 函数,我们使用 corset (或实际上已完成的它的子集)进行快速开发,使用合理的属性名称定义模型,使用 modelFormFactory 并且您可以即时编辑 UI。

I'm working on corset, a form library for backbone.js inspired by the django forms module, but a little less ambitious in scope. Still working out the kinks, but it'll end up on github when at least semi-stable and functional.

The aim of corset is to have easily subclassed field classes so that you can build complex inputs for more complex use cases (cascading selects, etc). This approach renders each field as a separate view, and the form view is bound to a model and uses change events, blur events or submit events to update the model (configurable, blur is default). Each view has an overrideable getData function that per default maps to the jquery .val() function.

Using sensible defaults and a modelFormFactory function, we use corset (or the subset of it that is actually done yet) for rapid development, define a model using sensible attribute names, use modelFormFactory and you have instant edit UI.

嗫嚅 2024-10-07 09:09:24

我在我的网站上创建了以下技术

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) 

,我在我的博客上详细介绍了您需要进行的骨干扩展

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

它使用与 events 属性相同的声明式样式来绑定表单元素
对属性进行建模

,这里是在 CoffeeScript Appologies 中为您实现该类的实际代码

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

    @

,如果您不喜欢 Coffeescript 。我愿意。每个人都不一样:)

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文