简体   繁体   English

JSON到Backbone.js模型

[英]JSON to Backbone.js Model

How can I send JSON to the initialization of a model? 如何将JSON发送到模型的初始化? I am trying to make the model dynamic based on a form: 我试图根据表单使模型动态:

v = new ModelObject($('#form-id').serializeJSON());

But this stores the form data as just one attribute and an object. 但是这将表单数据存储为一个属性和一个对象。 I'd like to use the JSON attributes as the model attributes. 我想使用JSON属性作为模型属性。

You'll need to get a better serializer. 你需要一个更好的序列化器。 I built one called Syphon, specifically to do this with backbone: 我建了一个叫Siphon,特别是用骨干来做这件事:

https://github.com/derickbailey/backbone.syphon https://github.com/derickbailey/backbone.syphon


var data = Backbone.Syphon.serialize(someViewWithAForm);

var model = new Backbone.Model(data);

Or Ben Alman's serializeObject jQuery extension: http://benalman.com/projects/jquery-misc-plugins/#serializeobject 或者Ben Alman的serializeObject jQuery扩展: http//benalman.com/projects/jquery-misc-plugins/#serializeobject

You can populate the model with form data by using this code: 您可以使用以下代码使用表单数据填充模型:

var data = {};
$.each(this.$("#formId").serializeArray(), function(index, val) {
  data[val.name] = val.value;
});

then call save or init the moduel with the data. 然后用数据调用save或init模块。

var demo = new My.Dynamic.Model(data);

or 要么

var demo = new My.Dynamic.Model();
demo.save(data);

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

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