13

假设我有这样的 json 设置:

{
  page:1,   
  items:[
    {  
      name: 'item1', 
      id:1
    }, 
    {
      name: 'item1', 
      id:2
    }, 
    {
      name: 'item1', 
      id:3
    }
  ] 
}

和这样的建模:

var Item = Backbone.Model.extend({
    defaults: {name:  "No name"}
});

var ItemCollection = Backbone.Collection.extend({
    model: Item,
    url: '/some/ajax/url',
});

获取此 json 后,如何将项目集映射为 ItemCollection 的集合并将页码作为属性添加到集合中?

4

2 回答 2

26

正如@asawyer 提到的,您必须重写 parse 方法,但您不需要实际实例化每个项目,如果您返回项目数组,Backbone 可以为您执行此操作。

请参阅collection.parse的文档

解析 collection.parse(response)

每当服务器返回集合的模型时,Backbone 都会在 fetch 中调用 parse。该函数传递原始响应对象,并应返回要添加到集合中的模型属性数组。

你的代码可以写成

var ItemCollection = Backbone.Collection.extend({
    model: Item,
    url: '/some/ajax/url',

    parse: function(data) {
        this.page=data.page;
        return data.items;
    }
});
于 2012-04-05T10:53:09.503 回答
2

您需要覆盖解析

它最终会看起来像这样:

class Item extends Backbone.Model
    defaults:
        name: "No name"

class ItemCollection extends Backbone.Collection
    model: Item
    url: '/some/ajax/url'
    parse: (data) ->
        items = []
        _.each data, (item) ->
            newItem = new Item
                id: item.id
                name: item.name
            items.push newitem
        items

(Coffeescript,但很容易转换为直接的 javascript)

您的另一个选择是在以下位置找到的关系插件:

https://github.com/PaulUithol/Backbone-relational

我从来没有使用过它,但我认为它应该为你做解析映射的东西。

于 2012-04-04T22:37:53.253 回答