Backbone:使用setInterval

时间:2013-08-22 17:41:50

标签: javascript backbone.js setinterval

我需要视图来重新收集集合并每30秒重新渲染一次。问题是,一旦我更改页面(没有完整页面刷新),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;
            }
        });
    }
);

3 个答案:

答案 0 :(得分:9)

timer变量分配给setInterval,并在关闭视图时将其清除。

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

或者如果你有一个在关闭视图时调用的自定义原型方法,那么只需包含它并且应该清除计时器。

但请确保在移动到下一页之前清理视图,如果不处理,将导致内存泄漏,从而大大减慢应用程序的运行速度。

最好将事件直接附加到视图,而不是使用model

collectionlistenTo

替换

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

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

这样,如果删除视图,即使是事件绑定也会被处理掉。否则,您需要明确取消绑定集合上的事件。

只需调用this.stopListening()即可解除对视图中所有事件的绑定。

答案 1 :(得分: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 );  
    }

答案 2 :(得分:0)

首先,您需要获取间隔的参考并保存,以便以后可以停止。 setInterval为此返回一个区间ID

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

然后当你想要停止它时(我假设你想要在undelegate事件事件中停止它,因为它听起来像你正在隐藏/重新显示视图)

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