更新主干集合

时间:2013-03-07 05:54:36

标签: javascript jquery backbone.js

我有一个Restful服务,它返回一个JSON对象数组。该服务允许用户指定最大结果和数据分页。我将此服务映射到集合,并默认将max_result设置为10和第1页。我现在想要从下一页获取数据并更新/更改集合中的模型,我该如何实现这一目标。 Backbone Collection:

define(['backbone','models/Video'],function(Backbone,Video) {
return Rock = Backbone.Collection.extend ({
    model:Video,
    url:"/root/max_result/page"
});
});

1 个答案:

答案 0 :(得分:1)

因此第2页的网址会显示为'/root/10/2'吗?

define(['backbone','models/Video'],function(Backbone,Video) {
  return Videos = Backbone.Collection.extend ({
    model:Video,
    initialize: function(models, options){
        // get options.genre or use 'rock' as default
        this.genre = options && _.has(options, 'genre') ? options.genre : 'rock';
    },
    fetch: function(options){
       // make sure we have options object
       options = options ? _.clone(options) : {};

       // if no url in options, create url using options.page
       if(!_.has(options, 'url')){
         options.url = "/" + this.genre + "/10/" + options && _.has(options, 'page') ? options.page : 1;
       }

       return Backbone.Collection.prototype.fetch.apply(this, [options]);
    }
  });
});

// fetch page 3
var rock = new Videos(null, {genre: 'rock'});
rock.on('reset', function(){
    // each time you fetch, this will be called.
});
rock.fetch({page:3});