javascript - 更新主干模型/ View 的轮询请求

标签 javascript backbone.js websocket long-polling polling

我需要找到一种方法来更新使用 backbone 实现的网络应用程序。

用例如下:
我有几个 View ,每个 View ,或者可能与这个 View 相关的模型/集合, 需要在不同的时间向服务器发出不同的轮询请求以发现一些变化。

我想知道最通用的方法是什么:

1) 实现传统轮询请求
2) 实现长轮询请求
3) 实现 HTML5 网络套接字


附言:
1) 服务器是用PHP编写的。
2) 现在我正在寻找不使用 HTML5 WebSockets 的解决方案,因为使用 PHP 可能不是那么简单。


这是我使用 Traditional Polling Request 的简单代码 (1)。

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

最佳答案

在你的模型中实现轮询处理程序,检查这个例子:

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

关于javascript - 更新主干模型/ View 的轮询请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11450461/

相关文章:

javascript - backbone.js View 继承。 `this` 父级分辨率

javascript - Backbone.js 在获取返回值后呈现 View

django - 混合 Websocket 和 REST

python - 在 Python 3 中使用 asyncio 和 websockets 的长时间延迟

javascript - 在javascript中将对象作为参数传递的性能

javascript - 使用 datatable.js 过滤名字和姓氏

javascript - 如何渲染路线 View ?

javascript - 使用 ng-repeat 创建元素后正确跟踪对象 ID

javascript - 为什么我的函数返回与 Chrome 浏览器中的 console.log() 不同

php - 如何纠正 [PHP fatal error : Interface 'Ratchet\MessageComponentInterface' not found ] in ratchet