2017-06-14 43 views
1

我有一個從API端點填充的Backbone集合。這回的數據,如:骨幹 - 使用另一個API調用的數據更新集合中的模型

[ 
    { 
     "gameId": 1234, 
     "gameName": "Fun Game 1" 
    }, 
    { 
     "gameId": 1235, 
     "gameName": "Fun Game 2" 
    }, 
    { 
     "gameId": 1236, 
     "gameName": "Fun Game 3" 
    }, 
    etc, 
    etc, 
    etc 
] 

收集非常簡單,在路由器被初始化所以這是整個應用程序可以訪問:

var GamesCollection = Backbone.Collection.extend({ 
     model: GameModel, 
     url: '/path/to/games/list', 

     parse:function(response){ 
      return response; 
     } 
    }); 

我有另一個端點返回的相關數據的收集到原始數據。這個數據是這樣的:

[ 
    { 
     "gameId": 1234, 
     "numberOfPlayers": "1,000" 
    }, 
    { 
     "gameId": 1235, 
     "numberOfPlayers": "Fun Game 2" 
    }, 
    { 
     "gameId": 9999, 
     "numberOfPlayers": "Some other game that's not in the original list" 
    } 
] 

注意,number of players響應可能會或可能不包含數據在原始響應每場比賽可能會或可能不包含數據的遊戲,不要在原創遊戲的反應存在。

我需要每隔X分鐘輪詢number of players端點,並使用響應中的數據更新GamesCollection中的模型,以便我可以在視圖中顯示它。

處理這個問題的最佳方法是什麼?

回答

1

查詢您的numberOfPlayers端點,然後查詢set the fetched data on your collection。您可以自定義set如何與addremove選項配合使用。

例如,

var GamesCollection = Backbone.Collection.extend({ 
    model: GameModel, 
    url: '/path/to/games/list', 

    parse: function(response){ 
     return response; 
    }, 

    pollNumberOfPlayers: function() { 
     var self = this; 
     return Backbone.ajax('/numberOfPlayers/endpoint').then(function(resp) { 
      self.set(resp, {add: false, remove: false, merge: true}); 
     }); 
    }, 

    startPolling: function() { 
     var self = this, 
      timer = 10000; //10 seconds 

     self.pollNumberOfPlayers().then(function() { 
      setTimeout(function() { 
       self.startPolling(); 
      }, timer); 
     }); 
    } 
}); 

請注意,我假定你GameModel對象具有gameId作爲其idAttribute