Backbone.js的撷取一个更复杂的数据,并使用作为一个集合 [英] Backbone.js Fetching a more complex data and using as a collection

查看:54
本文介绍了Backbone.js的撷取一个更复杂的数据,并使用作为一个集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Assume I have a such json setting:

{
  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收集的物品,并添加页码为集合属性?

After fetching this json, how can I map the items set as the collection of the ItemCollection and add the page number as an attribute to the collection?

推荐答案

由于@asawyer提到的,你必须覆盖解析方法,但你并不需要真正实例化的每个项目,骨干可如果你这样做对你返回项目的数组。

As @asawyer mentioned, you have to override the parse method, but you don't need to actually instantiate each item, Backbone can do that for you if you return the array of items.

请参见 collection.parse

解析 collection.parse(响应)

解析被称为骨干每当
  集合的模型是由服务器返回,在取。功能
  传递的原始响应对象,并应的返回模型的属性数组添加的到集合中。

parse is called by Backbone whenever a collection's models are returned by the server, in fetch. The function is passed the raw response object, and should return the array of model attributes to be added to the collection.

您code可以写成

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

    parse: function(data) {
        this.page=data.page;
        return data.items;
    }
});

这篇关于Backbone.js的撷取一个更复杂的数据,并使用作为一个集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆