简体   繁体   English

Backbone-使用嵌套的json数据将表单提交绑定回模型

[英]Backbone - Binding form submission back to model with nested json data

I've been racking my brain over this issue for a few days and cant come up with a decent solution. 几天来,我一直在绞尽脑汁,无法提出一个体面的解决方案。

I have the following model 我有以下型号

{
  "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": ""
     },
     ......
  ]
}

My view uses this model, and specifically the userPrefs, to create an edit form. 我的视图使用此模型(尤其是userPrefs)创建编辑表单。 So for example the userPrefs would generate an input like so 因此,例如,userPrefs将生成类似这样的输入

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

A user may then enter a value for first name - eg "John" and click save. 然后,用户可以输入名字的值-例如“ John”,然后单击“保存”。 I need to map this form data back to the model before issuing a PUT request. 在发出PUT请求之前,我需要将此表单数据映射回模型。

So I hijack the submit event and do 所以我劫持了提交事件并做

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

this returns me an array of key/value pairs eg 这给我返回了一组键/值对,例如

[{"firstName": "John"}]

Now the issue I'm having is how best to map these value's back into the correct userPref in the model. 现在,我面临的问题是如何最好地将这些值映射回模型中的正确userPref。

I toyed with the idea of 'assuming' 5 userPrefs would result in 5 inputs. 我玩弄了“假设” 5个userPrefs会产生5个输入的想法。 I could then just use an iterator with an index to update the correct userPref. 然后,我可以只使用带有索引的迭代器来更新正确的userPref。 But as we know, an unchecked checkbox wont be submitted, so a simple iterator wont work. 但是,正如我们所知,不会提交未选中的复选框,因此简单的迭代器将无法工作。

Then I tried taking each serialised value and looping through the userPrefs for a match. 然后,我尝试获取每个序列化的值并遍历userPrefs以进行匹配。 But this would still fall over with the checkbox issue mentioned above. 但这仍然会因上述复选框问题而失效。

Can anyone see an elegant solution to this? 谁能看到一个优雅的解决方案?

  • Is there a better json structure I should be using to get round this issue? 我应该使用更好的json结构来解决此问题吗? perhaps a separate model containing only userPrefs 也许是仅包含userPrefs的单独模型
  • How will I know if a user has unchecked a checkbox and be able to update my model 我如何知道用户是否取消选中复选框并能够更新我的模型

I came up with a fairly simple solution in the end. 最后,我想出了一个相当简单的解决方案。

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

Because I used each userPref to build the form in the first place, I can loop through them and query the dom. 因为我首先使用了每个userPref来构建表单,所以我可以遍历它们并查询dom。

I can then insert the value back into the model. 然后,我可以将值重新插入模型中。

It has 2 downsides that I can see 我可以看到2个缺点

  • I'm updating the value in the model regardless of whether it has actually changed 我正在更新模型中的值,而不管它是否实际上已更改
  • It has a hard coded check for checkboxes 它具有复选框的硬编码复选框

But for my use case this is acceptable. 但是对于我的用例,这是可以接受的。

Here is the solution that I can think of. 这是我能想到的解决方案。 First thing is you should not have simple JSON as your model rather have an association (one-to-many, model to userPrefs ). 第一件事是您不应将简单的JSON作为模型,而应具有关联(一对多, model to userPrefs )。 Have a look at Backbone Associations to establish the relationship. 看一下骨干协会来建立关系。 In Backbone Associations context you need to have a AssociatedModel created for your outer model and userPref and then add userPrefs collection into your outer model. Backbone Associations上下文中,您需要为外部modeluserPref创建一个AssociatedModel ,然后将userPrefs集合添加到外部模型中。 (This is explained in Backbone Associations tutorials.) (这在骨干协会教程中进行了解释。)

When you create edit form from a specific userPref model store the id of this model somewhere in the form (a hidden field or data attribute) so that you can use it later to find the respective userPref model from userPrefs collection and update accordingly. 当您从特定的userPref模型创建edit formuserPref模型的id存储在表单中的某个位置(隐藏字段或数据属性),以便以后可以使用它从userPrefs集合中查找相应的userPref模型并进行相应的更新。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM