javascript - Backbone - 使用从另一个 API 轮询的数据更新集合中的模型

标签 javascript backbone.js backbone.js-collections

我有一个从 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如何与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

关于javascript - Backbone - 使用从另一个 API 轮询的数据更新集合中的模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44543483/

相关文章:

javascript - 如何确保文本框中的 whaveter 仅是二进制的 1's and 0' s?

javascript - Require.js 和可重用的 UI 函数

javascript - 通过 console.log() 打印 Backbone.js 集合,这是怎么回事?

javascript - 模型中的 Backbone 集合 + 使用 Node.js 的 Restful 服务器设计

javascript - Backbone.js 集合选项

javascript - 在 AngularJS 中加载本周的数据

javascript - Angular 4 上下文中的 "deep import"是什么?

javascript - Blackberry webworks 和 Phonegap 不执行 <script> 标签

javascript - 覆盖主干的解析函数

javascript - 将模型添加到集合会引发错误 "Uncaught TypeError: Cannot read property ' idAttribute' of undefined"