how to do polling in backbone.js?

試著忘記壹切 提交于 2020-01-01 07:03:34

问题


Hi i am working on a paly2.0 framework application(with java) using backbone.js. In my application i need to get the table data from the database regularly ( for the use case of displaying the upcoming events list and if the crossed the old event should be removed from the list ).I am getting the data to display ,but the issue is to hit the Database regularly.For that i tried use backbone.js polling concept as per these links Polling a Collection with Backbone.js , http://kilon.org/blog/2012/02/backbone-poller/ .But they not polling the latest collection from db. Kindly suggest me how to achieve that or any other alternatives ? Thanks in adv.


回答1:


There is not a native way to do it with Backbone. But you could implement long polling requests adding some methods to your collection:

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


来源:https://stackoverflow.com/questions/11718301/how-to-do-polling-in-backbone-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!