Jonatan Littke
Jonatan Littke

Reputation: 5663

BackboneJS - cacheing view instances

I'm writing a BackboneJS app where each of six tabs are represented by their own views. Am I supposed to save the instance of the view and just call it's render() function whenever a user hits a tab he's already been to? Or create a new instance and access the template that jQuery cached for me during the first rendering?

If I do the latter, I would still need to make sure another collection isn't fetched through my JSON API, since that's done during initialization of some views.

Right now I store all view instances in my controller but I was wondering if this was built-in somehow or there are better alternatives.

Cheers.

Update: Here's my loadCachedView function that I use in my controller:

loadCachedView: function (name, view, collection){
    if (!this.views[name]){
        if (collection){
            this.collections[name] = new collection();
        }
        this.views[name] = new view({collection: this.collections[name]});
    } else {
        this.views[name].render();
    }
},

So when rendering a view, I just go: this.loadCachedView('settings', SettingsView, SettingsCollcetion).

Upvotes: 3

Views: 361

Answers (2)

Julien
Julien

Reputation: 9216

I usually keep track of all my views in my controller. The controller then switch between available views based on the nav events:

var Switches;
Switches = [];
Skepic.SwitchView = Backbone.View.extend({
    hide: function() {
        return this.el.detach();
    },
    show: function() {
        if (!_.include(Switches, this)) {
            Switches.push(this);
        }
        _.each(Switches, function(s) {
            return s.hide();
        });
        this.container().append(this.el);
        return $('html, body').animate({
            scrollTop: 0
        }, 'fast', "linear");
    },
    container: function() {
        if (this.options.container) {
            return this.options.container;
        } else {
            return $("body > .content");
        }
    }
});

This is kind of the base view to switch between one view and the other. The controller will create the view (fetching data as needed) and when you switch, you can do your last checks in an overriden show() function in the view.

(notice I use detach on the jQuery to still have the event delegation working)

Upvotes: 3

Jess Jacobs
Jess Jacobs

Reputation: 1137

Couldn't you make use of the .memoize function here?

Upvotes: 1

Related Questions