最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Backbone: Wait for multiple fetch to continue - Stack Overflow

programmeradmin3浏览0评论

I fetch collection of multiple pages and I am looking for a way to know when all fetchs are done. Here is what my collection looks like:

app.collections.Repos = Backbone.Collection.extend({
  model: app.models.Repo,
  initialize: function(last_page){
    this.url = ('/' + app.current_user + '/watched');

    for (var i = 1; i <= last_page; i++) {
      this.fetch({add: true, data: {page: i}});  
    };
  }, ...

Any idea how I could achieve this with clean code?

I fetch collection of multiple pages and I am looking for a way to know when all fetchs are done. Here is what my collection looks like:

app.collections.Repos = Backbone.Collection.extend({
  model: app.models.Repo,
  initialize: function(last_page){
    this.url = ('https://api.github./users/' + app.current_user + '/watched');

    for (var i = 1; i <= last_page; i++) {
      this.fetch({add: true, data: {page: i}});  
    };
  }, ...

Any idea how I could achieve this with clean code?

Share Improve this question edited Aug 23, 2012 at 3:41 Barlas Apaydin 7,31511 gold badges58 silver badges88 bronze badges asked Aug 23, 2012 at 3:33 GregoryGregory 5696 silver badges18 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 14

Use jQuery deferreds:

var deferreds = [];
for (var i = 1; i <= last_page; i++) {
  deferreds.push(this.fetch({add: true, data: {page: i}}));
};

$.when.apply($, deferreds).done(function() {
  ...
  <CODE HERE>
  ...
}

(I haven't actually tested this but I think it should work.)

jQuery documentation on when:

Provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events.

And another answer that might help: How do you work with an array of jQuery Deferreds?

One option is to use underscore.js' after -function (docs), but that necessitates using a success -callback, because there will be A LOT of add -events:

initialize: function(last_page){
  this.url = ('https://api.github./users/' + app.current_user + '/watched');

  var self = this; // save a reference to this

  var successCallback = _.after(function() {

    self.trigger('allPagesFetched'); //trigger event to notify all listeners that fetches are done

  }, last_page); // this function will be called when it has been called last_page times

  for (var i = 1; i <= last_page; i++) {
    this.fetch({add: true, data: {page: i}, success: successCallback});  
  };
},

Hope this helped!

发布评论

评论列表(0)

  1. 暂无评论