2

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.

Community
  • 1
  • 1
  • 2
    What do you mean with _"they not polling the latest collection from db"_. Backbone will use the data your server is sending, if the data sent is not the one you expect the problem can be in the server side. – fguillen Jul 30 '12 at 09:39
  • Thank you for responding .server is sending the data, i mean to say i want to hit the database regularly with 1 min duration – vishnu brundavanam Jul 30 '12 at 10:43

1 Answers1

8

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'); });
Daniel Aranda
  • 6,426
  • 2
  • 21
  • 28
  • Just want to note that triggering your own `'collectionFetched'` is probably unneeded since it will trigger `'reset'` already, and that will be more generally useful anyway. – loganfsmyth Jul 31 '12 at 02:34
  • I agree, I could update it. :D The sense is the same, Thank You! – Daniel Aranda Jul 31 '12 at 02:59