Search code examples
javascriptbackbone.jswebsocketlong-pollingpolling

Polling request for updating Backbone Models/Views


I need to find a way to update a web App implemented with backbone.

The use case will be the following:
I have several Views, and each View, or maybe model/collection related to this view, needs to make different polling request to the server at different time for discovering some change.

I am wondering what is the most general way to:

1) implement the Traditional Polling Request
2) implement the Long Polling Request
3) implement the HTML5 web socket


P.S.:
1) The server is written in PHP.
2) For now I am looking for a solution without using HTML5 WebSockets because maybe with PHP is not so simple.


Here's my simple code (1) using Traditional Polling Request.

(1)

// MyModel
var MyModel = Backbone.View.extend({
    urlRoot: 'backendUrl'
});

// MyView
var MyView = Backbone.View.extend({

    initialize: function () {
        this.model = new MyModel();
        this.model.fetch();
        this.model.on('change', this.render);
        setTimeout(function () {
            this.model.fetch();
        }, 1000 * 60 * 2); // in order to update the view each two minutes
    }
});


Solution

  • Implement it in your Model the polling handler, check this example:

    // MyModel
    var MyModel = Backbone.Model.extend({
      urlRoot: 'backendUrl',
    
      //Add this to your model:
      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
        }
      }
    });
    
    // MyView
    var MyView = Backbone.View.extend({
    
        initialize: function () {
            this.model = new MyModel();
            this.model.startLongPolling();
            this.model.on('change', this.render);
        }
    });