如何在backbone.js中进行轮询?

vis*_*nam 2 polling poller backbone.js play2-mini

嗨,我正在使用backbone.js在paly2.0框架应用程序(使用java)上工作.在我的应用程序中,我需要定期从数据库中获取表数据(对于显示即将发生的事件列表的用例以及是否应该从列表中删除旧事件).我正在显示数据,但是问题是定期访问数据库.为此我尝试使用backbone.js轮询概念按照这些链接使用Backbone.js轮询集合,http://kilon.org/blog/2012/02/backbone-poller/ .But他们没有从db中查询最新的集合.请建议我如何实现这个或任何其他选择?谢谢你.

Dan*_*nda 8

使用Backbone没有本地方法.但您可以实现长轮询请求,为您的集合添加一些方法:

// MyCollection
var MyCollection = Backbone.Collection.extend({
  urlRoot: 'backendUrl',

  longPolling : false,
  intervalMinutes : 2,
  initialize : function(){
    _.bindAll(this);
  },
  startLongPolling : function(intervalMinutes){
    this.longPolling = true;
    if( intervalMinutes ){
      this.intervalMinutes = intervalMinutes;
    }
    this.executeLongPolling();
  },
  stopLongPolling : function(){
    this.longPolling = false;
  },
  executeLongPolling : function(){
    this.fetch({success : this.onFetch});
  },
  onFetch : function () {
    if( this.longPolling ){
      setTimeout(this.executeLongPolling, 1000 * 60 * this.intervalMinutes); // in order to update the view each N minutes
    }
  }
});

var collection = new MyCollection();
collection.startLongPolling();
collection.on('reset', function(){ console.log('Collection fetched'); });
Run Code Online (Sandbox Code Playgroud)