javascript 使用接收到的 JSON 数据创建主干模型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10914166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating Backbone Model using received JSON data
提问by jaks
I know how to create a new backbone model. But how I can create a backbone model with the data which is received from a web service?
我知道如何创建一个新的主干模型。但是如何使用从 Web 服务接收到的数据创建主干模型?
For example, you are receiving a JSON data from a webservice. I want to use this JSON as backbone model. How I can do that?
例如,您从 Web 服务接收 JSON 数据。我想使用这个 JSON 作为主干模型。我怎么能做到这一点?
Thanks.
谢谢。
回答by Derick Bailey
MyModel = Backbone.Model.extend({});
var data = { /* some data you got from the ajax call */};
var m = new MyModel(data);
Or if you don't need a specific type of model, you can just use a generic Backbone.Model
或者,如果您不需要特定类型的模型,则可以使用通用的 Backbone.Model
var data = { /* some data you got from the ajax call */};
var m = new Backbone.Model(data);
回答by gion_13
It's not clear if you're trying to create a model definition or a model instance.
Either way, if your service is returning a json object, somehing like should work:
不清楚您是在尝试创建模型定义还是模型实例。
无论哪种方式,如果您的服务返回一个 json 对象,那么应该可以:
var data = {/*received data*/};
// for a new model definition
var newModelDefinition = Backbone.Model.extend(data);
// that you can instantiate later on:
var model1 = new newModelDefinition(),
model2 = new newModelDefinition(someData);
// for a new model instance
var newModelInstance = new Backbone.Model(data);