2013-10-09 115 views
0

我創建了一個骨幹模型,它從服務器獲取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(); 
     }); 

     }); 
+0

您是否正在尋找一種方法在不刷新數據的情況下每N毫秒重新渲染一次視圖?或者你正在尋找一種方法來每N毫秒刷新一次數據(然後是託管它的視圖)? – thibauts

回答

1

一個簡單的解決辦法是:

profiles.fetch({reset: true}); 

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

我不會說這是一個漂亮的解決方案,但我希望你的想法。據我所知,在Backbone中沒有間隔獲取或類似的東西 - 所以你幾乎必須建立自己的。

編輯

這可能是一個更好的解決辦法,我喜歡它更ATLEAST。

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速度較慢,這非常方便。

+0

好吧,這是我想與一個輕微的差異。上面,創建了多個profileTemplate,結果我每隔7秒就有一個接一個的多個div。我怎樣才能每次存儲一個profileTemplate並更改它?我如何更改內容並不追加內容? –

+0

我只是改變附加()與HTML()函數,它的工作原理! –