Backbone.js 获取更复杂的数据并用作集合 [英] Backbone.js Fetching a more complex data and using as a collection

查看:18
本文介绍了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 提到的,你必须重写 parse 方法,但你不需要实际实例化每个项目,Backbone 可以为你做到这一点,如果你返回项目数组.

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(response)

parse 被 Backbone 调用集合的模型由服务器在 fetch 中返回.功能传递原始响应对象,并且应该返回要添加到集合中的模型属性数组.

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.

你的代码可以写成

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天全站免登陆