我有一个从 API 端点填充的 Backbone 集合。返回数据如:
[
{
"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"
}
]
请注意,玩家数量
响应可能包含也可能不包含原始响应中每个游戏的数据,并且可能包含也可能不包含原始游戏响应中不存在的游戏的数据。
我需要每 X 分钟轮询一次玩家数量
端点,并使用响应中的数据更新 GamesCollection 中的模型,以便我可以在 View 中显示它。
处理这个问题的最佳方法是什么?
最佳答案
查询您的 numberOfPlayers
端点,然后 set
the fetched data on your collection 。您可以自定义set
如何与add
和remove
选项配合使用。
例如,
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
。
关于javascript - Backbone - 使用从另一个 API 轮询的数据更新集合中的模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44543483/