Backbone.js获取更复杂的数据并用作集合

Hel*_*nar 13 backbone.js

假设我有一个这样的json设置:

{
  page:1,   
  items:[
    {  
      name: 'item1', 
      id:1
    }, 
    {
      name: 'item1', 
      id:2
    }, 
    {
      name: 'item1', 
      id:3
    }
  ] 
}
Run Code Online (Sandbox Code Playgroud)

这样的建模:

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

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

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

nik*_*shr 26

正如@asawyer所提到的,你必须覆盖parse方法,但是你不需要实际实例化每个项目,如果你返回项目数组,Backbone可以为你做.

请参阅collection.parse的文档

解析 collection.parse(response)

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

你的代码可以写成

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

    parse: function(data) {
        this.page=data.page;
        return data.items;
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 你刚刚节省了我几个小时的工作.> _ < (2认同)