【问题标题】:Backbone - Binding form submission back to model with nested json dataBackbone - 使用嵌套的 json 数据将表单提交绑定回模型
【发布时间】:2013-09-18 10:54:47
【问题描述】:

几天来我一直在为这个问题绞尽脑汁,却想不出一个像样的解决方案。

我有以下型号

{
  "id": "123",
  "key1": "foo",
  "key2": "bar",
  "metadata": {
    "height": 1,
    "width": 1  
  },
  "userPrefs": [
     {
       "name":"firstName",
       "displayName":"First name",
       "required":true,
       "dataType":"text",
       "defaultValue":"enter first name",
       "value": ""
     },
     ......
  ]
}

我的视图使用这个模型,特别是 userPrefs,来创建一个编辑表单。因此,例如 userPrefs 会生成这样的输入

<input type="text" id="firstName" name="firstName" value="" placeholder="enter first name" required />

然后用户可以输入名字的值 - 例如“约翰”,然后单击保存。在发出 PUT 请求之前,我需要将此表单数据映射回模型。

所以我劫持了提交事件并做

this.$('form').serializeArray()

这会返回一个键/值对数组,例如

[{"firstName": "John"}]

现在我遇到的问题是如何最好地将这些值映射回模型中正确的 userPref。

我玩弄了“假设”5 个 userPrefs 会导致 5 个输入的想法。然后我可以使用带有索引的迭代器来更新正确的 userPref。但是我们知道,一个未选中的复选框不会被提交,所以一个简单的迭代器是行不通的。

然后我尝试获取每个序列化值并循环通过 userPrefs 进行匹配。但这仍然会因上面提到的复选框问题而失败。

谁能看到一个优雅的解决方案?

  • 我应该使用更好的 json 结构来解决这个问题吗?可能是一个仅包含 userPrefs 的单独模型
  • 我如何知道用户是否取消选中复选框并能够更新我的模型

【问题讨论】:

    标签: javascript json forms backbone.js backbone-model


    【解决方案1】:

    最后我想出了一个相当简单的解决方案。

    var self = this;
    var userPrefs = this.model.get('userPrefs');
    
    // loop through the prefs and update one at a time....
    _.each(userPrefs, function(pref, index) {       
       var item = self.$('#' + userPrefs[index].name); // userPref DOM item
       if (item[0].type === 'checkbox') {
          userPrefs[index].value = item[0].checked;
       } else {
          userPrefs[index].value = item[0].value;
       }
    });
    
    // update the model 
    this.model.set('userPrefs', userPrefs);
    

    因为我首先使用了每个 userPref 来构建表单,所以我可以遍历它们并查询 dom。

    然后我可以将值重新插入模型中。

    我可以看到它有 2 个缺点

    • 我正在更新模型中的值,无论它是否实际发生了变化
    • 它有一个硬编码的复选框检查

    但对于我的用例,这是可以接受的。

    【讨论】:

      【解决方案2】:

      这是我能想到的解决方案。首先,您不应该将简单的 JSON 作为模型,而应该有关联(一对多,model to userPrefs)。查看Backbone Associations 以建立关系。在Backbone Associations 上下文中,您需要为外部modeluserPref 创建AssociatedModel,然后将userPrefs 集合添加到外部模型中。 (这在 Backbone Associations 教程中进行了解释。)

      当您从特定的userPref 模型创建edit form 时,将此模型的id 存储在表单中的某处(隐藏字段或数据属性),以便您以后可以使用它来查找相应的userPref模型来自userPrefs 集合并相应更新。

      希望这会有所帮助。

      【讨论】:

      • 感谢您的建议。我喜欢使用嵌套模型和关联来改进架构的想法。但是我不确定它将如何解决将表单数据映射回模型的问题?也许我错过了什么?
      • 我已经在第二段解释过了。请查看教程以将模型设置回您的 userPrefs 集合。
      猜你喜欢
      • 2013-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-02
      • 1970-01-01
      • 2014-07-31
      • 1970-01-01
      相关资源
      最近更新 更多