** JSON 数据 **
{
"data" : [{
"book" : "first book", -- > i want this via model.get('book');
"aurthor" : "xyz"
}
]
}
** 使用 jquery Ajax 获取 json 数据。 **
var jsonData = {};
$.ajax({
url : 'booklist.json',
async : false,
dataType : 'json',
success : function (json) {
jsonData = json.data;
}
});
** 此处的模型声明 **
var MyModels = Backbone.Model.extend({
initialize : function () {},
defaults : {}
});
var modelinstance = new MyModels(jsonData);
modelinstance.get('book'); // it is giving undefined how can i get this value.
** 请帮助我做错的地方。我是 Backbone 的新手。 **
最佳答案
如果数据始终是像这样包装的单个对象,那么您只需添加 parse
method到您的模式:
parse
model.parse(response, options)
parse is called whenever a model's data is returned by the server, in fetch, and save. The function is passed the raw
response
object, and should return the attributes hash to be set on the model.
类似这样的事情:
parse: function(response) {
return response.data[0];
}
您还可以通过 model constructor 触发 parse
调用使用 parse: true
选项:
constructor / initialize
new Model([attributes], [options])
[...]
If{parse: true}
is passed as an option, the attributes will first be converted by parse before being set on the model.
因此,如果您通过 $.ajax
调用手动加载数据,那么您将得到如下所示的结果:
success: function (json) {
var m = new MyModel(json, { parse: true });
// Do something with m...
}
关于javascript - 如何从 Backbone 中嵌套的 json 对象获取模型属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18841868/