Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone: using setInterval

I need the view to refetched the collection and re-render every 30 seconds. The problem is that once I change page (without a full page refresh) the setInterval stays on memory and keeps refetching in the background. However the view has long been destroyed.

Code:

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;
            }
        });
    }
);
like image 989
azz0r Avatar asked Dec 04 '25 10:12

azz0r


1 Answers

Assign a timer variable to the setInterval and clear it out when you close the view.

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

Or if you have a custom prototype method that is called when a view is closed, then just include it and the timer should be cleared out.

But make sure, you clean up the views before you move to the next page, which when not handled will cause memory leaks that would drastically slow down your application.

And it is always a better idea to attach the events to the views directly, instead of a model or a collection using listenTo

Replace

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

with

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

This way if you remove the view, even the event bindings would be taken care off. Otherwise you would need to explicitly unbind the events on the collection.

Just calling this.stopListening() would take care of unbinding all the events on the view.

like image 114
Sushanth -- Avatar answered Dec 07 '25 01:12

Sushanth --



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!