使用 JSON 对象自动填充 Backbone.Collection
//Model
var Dog = Backbone.Model.extend({
name:'',
breed:''
});
//Collection
var Dogs = Backbone.Collection.extend({
model : Dog,
url : '/dogs'
parse : function(res)
{
alert('response' + res);
return res;
}
});
这是我从服务器收到的 JSON 对象,它是使用 Jersey 实现的。 我从服务器返回一个 DogModel 列表,它被转换为 JSON
@Produces(MediaType.APPLICATION_JSON)
{"DogModel":[{"name":"Jane","breed":"Great Dane"},
{"name":"Rocky","breed":"golden Retriver"},
{"name":"Jim","breed":"Lab"}]}
奇迹我还没有正确理解 Collection 及其 url 属性的用法。 我的假设是,当在 Collection 上调用 fetch 时,它会从服务器获取狗的详细信息并填充集合。
我确实得到了如上所述的响应,但该集合未按预期填充。
我应该怎么做才能使用集合自动填充模型列表? 我需要研究 JSON 对象的表示吗?
帮助赞赏!
//Model
var Dog = Backbone.Model.extend({
name:'',
breed:''
});
//Collection
var Dogs = Backbone.Collection.extend({
model : Dog,
url : '/dogs'
parse : function(res)
{
alert('response' + res);
return res;
}
});
This is the JSON objec that I receive from server which is implemented using Jersey.
I return a List of DogModel from Server, it is converted to JSON
@Produces(MediaType.APPLICATION_JSON)
{"DogModel":[{"name":"Jane","breed":"Great Dane"},
{"name":"Rocky","breed":"golden Retriver"},
{"name":"Jim","breed":"Lab"}]}
Wonder I haven't understood the usage of Collection and its url attribute correctly.
My assumption is that, when ever fetch is called on Collection, it'll fetch the dogs details from the server and populate the collection.
I do get the response as stated above but the collection is not populated as expected.
What should I do to automatically populate the list of models with the collection?
Do I need to work on the representation of JSON objects?
Help Appreciated!!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
parse
函数需要返回狗数组。因此,您可以按如下方式更新代码。附带说明一下,您希望在
defaults
哈希上声明模型的默认属性值,如下面的代码所示 (请参阅文档)The
parse
function needs to return the array of dogs. So you can update your code as follows.On a side note, you want to declare your model's default attribute values on the
defaults
hash like the code below shows (see documentation)