使用 JSON 对象自动填充 Backbone.Collection

发布于 2024-12-22 22:48:17 字数 743 浏览 0 评论 0原文

//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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

parse 函数需要返回狗数组。因此,您可以按如下方式更新代码。

parse : function(res) 
{
    alert('response' + res);
    return res.DogModel;
}

附带说明一下,您希望在 defaults 哈希上声明模型的默认属性值,如下面的代码所示 (请参阅文档

var Dog = Backbone.Model.extend({
  defaults: {    
    name:'',
    breed:''
  }
});

The parse function needs to return the array of dogs. So you can update your code as follows.

parse : function(res) 
{
    alert('response' + res);
    return res.DogModel;
}

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)

var Dog = Backbone.Model.extend({
  defaults: {    
    name:'',
    breed:''
  }
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文