2017-06-14 5 views
1

私はAPIエンドポイントからデータを取り込んでいるバックボーンコレクションを持っています。この戻りのようなデータ:バックボーン - 別の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; 
     } 
    }); 

私は、関連するデータのコレクションを返す別のエンドポイントを持っています元のデータに戻します。このデータは、次のようになります。

number of players応答がまたは元の応答ですべてのゲームのためのデータを含んでも含まなくてもよいし、あるいは、元のゲームの応答には存在していないゲームのためのデータを含んでも含まなくてもよいということ
[ 
    { 
     "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分ごとにポーリングし、レスポンスのデータでGamesCollectionのモデルを更新する必要があります。これをビューに表示することができます。

これを処理する最善の方法は何ですか?

答えて

1

numberOfPlayersエンドポイントとset the fetched data on your collectionを照会してください。 addremoveオプションを使用して、setの動作をカスタマイズすることができます。例えば

、私はあなたのGameModelオブジェクトは、idAttributeとしてgameIdを持っていると仮定

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); 
     }); 
    } 
}); 

注意。

関連する問題