簡體   English   中英

更新主干網視圖

[英]Update backbone View

我創建了一個主干模型,該模型從服務器獲取json。 但是,我想在特定的時間間隔而不是服務器每次發送數據時都用新數據更新視圖。 我應該使用什么來每n毫秒更新一次主干視圖? 我有上面的代碼。

    $(function() {


    var Profile = Backbone.Model.extend();

    var ProfileList = Backbone.Collection.extend({

                    model: Profile,
                    url: 'data.php'
    });   

    var ProfileView = Backbone.View.extend({

        el: "#profiles",
        template: _.template($('#profileTemplate').html()),
        render: function(eventName) {

        _.each(this.model.models, function(profile){
        var profileTemplate = this.template(profile.toJSON());
        $(this.el).append(profileTemplate);
        }, this);

            return this;

        }
    });

        var profiles = new ProfileList();    
        var profilesView = new ProfileView({model: profiles});

        profiles.fetch({reset: true});
        //profiles.bind('reset', function () { console.log(profiles); });
        profiles.bind('reset', function () {
                profilesView.render();
        });

      });

一個簡單的解決方案是:

profiles.fetch({reset: true});

setInterval(
  function() {
    profiles.fetch({reset: true});
  }, 1000 // Time in milliseconds
);

我不會說這是一個很好的解決方案,但希望您能理解。 據我所知,在Backbone中沒有實現間隔獲取或類似的操作-因此,您幾乎必須構建自己的間隔。

編輯

這可能是一個更好的解決方案,我至少喜歡它。

var ProfileList = Backbone.Collection.extend({
  model   : Profile,
  url     : "data.php",
  xhr     : null,
  interval: null,

  fetchWithInterval: function(options) {
    var options = options || {},
        self    = this;

    this.interval = setInterval(function(){
      if(self.xhr !== null && self.xhr.readyState !== 4) {
        return;
      }
      self.xhr = self.constructor.__super__.fetch.apply(self, options);
    }, 1000);

    this.xhr = self.constructor.__super__.fetch.apply(self, options);
  },

  stopFetchWithInterval: function() {
    clearInterval(this.interval);
  }
});

profiles.fetchWithInterval({reset: true}); 您可以使用profiles.stopFetchWithInterval()停止它。

它還管理xhr ,因此,如果AJAX調用未完成,它將不會開始新的調用。 如果您想以較小的間隔獲取數據,或者由於某種原因而使API速度緩慢時,這非常方便。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM