2013-08-22 53 views
3

我需要视图来重新绘制集合并每30秒重新渲染一次。问题是,一旦我改变页面(没有完整页面刷新),setInterval保留在内存上,并在后台继续重新绘制。然而这种观点早已被摧毁。骨干:使用setInterval

代码:

define(
    [ 
     "underscore", 
     "collection/system/feed", 
     "view/list", 
     "text!template/index/system-feed.html" 
    ], 
    function (_, Collection, ListView, Template) { 


     return ListView.extend({ 


      el:    '<div id="main-inner">', 
      collection:  new Collection(), 
      loading:  true, 
      client:   false, 


      initialize: function (options) { 

       this.collection.fetch(); 
       this.collection.on('reset', this.onFetchCollection, this); 

       var self = this; 
       setInterval(function() { 
        self.collection.fetch(); 
       }, 30000); 
      }, 


      /*collection is returned, so reset the loading symbol and set the posts to the render*/ 
      onFetchCollection: function() { 
       this.list = this.collection.toJSON(); 
       this.loading = false; 
       this.render(); 
      }, 


      render: function() { 
       var html = _.template(Template, {loading: this.loading, client: this.client, list: this.list}); 
       this.$el.html(html); 
       return this; 
      } 
     }); 
    } 
); 
+0

你知道*何时该视图被“销毁?”例如,如果在视图上调用remove(),则可以覆盖它并使用'clearInterval'来停止您的循环获取。 – Divey

+0

大约有55页,所以使用clearInterval会很困难,除非我使用间隔的标准名称。我猜。 – azz0r

+0

但是,每次关闭视图时(特别是当您有55页时),您确实应该调用'view.remove()'。除非泄漏是您的应用程序的功能之一。而'collection:new Collection()'不会做你可能认为它做的事。 –

回答

9

分配timer变量来的setInterval并清除出来,当你关闭视图。

initialize: function() { 
this.timer = setInterval(function() { 
     self.collection.fetch(); 
}, 30000); 
}, 
close: function() { 
    clearInterval(this.timer); 
} 

或者,如果你有一个自定义的原型方法,当一个视图关闭时被调用,那么就包括它和定时器应该被清除出去。

但是请确保在移动到下一页之前清理视图,如果未处理该视图将导致内存泄漏,从而大幅降低应用程序的速度。

而且它始终是一个更好的主意,事件直接连接到的意见,而不是modelcollection使用listenTo

更换

this.collection.on('reset', this.onFetchCollection, this); 

this.listenTo(this.collection, 'reset', this.onFetchCollection); 

这如果你删除视图,即使事件绑定将被关注。否则,您需要明确解除集合上的事件。

只要调用this.stopListening()就可以解除视图上所有事件的解除绑定。

+0

谢谢,这工作完美。 – azz0r

+0

@ azz0r ..很高兴有帮助:) –

0

您可以改用setTimeout。它可能看起来像这样。

return ListView.extend({.... 
    initialize: function() { 
     .... 
     var self = this; 
     self.fetchCollection(); 
    } 
    , fetchCollection: function() { 
     var self = this; 
     self.collection.fetch(); 

     this.timeout = setTimeout(function() { 
      self.fetchCollection 
     }, 30000); 
    } 
    , close: function() { 
     window.clearTimeout(this.timeout); 
    } 
0

首先,您需要获取间隔的参考并保存,以便稍后停止。 setInterval的返回间隔标识用于此目的

var self = this; 
self.interval = setInterval(function() { 
     self.collection.fetch(); 
    }, 30000); 

然后,当你想停止它(我假设你想停止它的undelegate事件的事件,因为它听起来像是你是隐藏/ reshowing视图)

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