更新主干模型/视图的轮询请求

2024-07-01

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

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

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

1)实施Traditional Polling Request
2)实施Long Polling Request
3)实施HTML5 web socket


P.S.:
1)服务器是用PHP编写的。
2) 现在我正在寻找一个不使用 HTML5 WebSockets 的解决方案,因为也许使用 PHP 并不那么简单。


这是我的简单代码 (1) 使用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
    }
});


在您的模型轮询处理程序中实现它,请检查以下示例:

// 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);
    }
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

更新主干模型/视图的轮询请求 的相关文章