MajinOLesedi
MajinOLesedi

Reputation: 3

Is this a best practice to cache request data in Backbone.js?

I have a requestCache: {} object in my router declaration. I have a reviews method mapped to a route with the same name (#reviews). I want to cache the results generated inside this method.

router.js

var AppRouter = Backbone.Router.extend({
        currentView: null,
requestCache: {},
reviews: function() {
        var self = this;
        var reviewCollection = new ReviewCollection();
        reviewCollection.url = '/profile/' + this.userid + '/reviews';
        if('reviews' in self.requestCache) {
            reviewCollection = self.requestCache['reviews'];
            self.changeView(new ReviewsView({collection:reviewCollection}), 'reviews');
        } else {
            reviewCollection.fetch().done(function() {
                self.requestCache['reviews'] = reviewCollection;
                self.changeView(new ReviewsView({collection:reviewCollection}), 'reviews');
            });
        }
    },

changeView just renders the view using the results. This works fine. What I want to know is whether this is a good way of caching data?

Upvotes: 0

Views: 114

Answers (2)

Walter Macambira
Walter Macambira

Reputation: 2605

As suggested by SoundCloud team, they've craeted a store object to share models and collections through the code.

I've been using Backbone SingletonModel (https://github.com/reconbot/backbone-singleton)

It works just fine and you can make the same for your collections, defining a getInstance method and a _instance on its static part.

var MyCollection = Backbone.Collection.extend({}, {

   _instance: null,
   count: 0,
   getInstance: function () {

      if (!this._instance)
          this._instance = new MyCollection();

      this.count++;

      return this._instance;

   }

});

Upvotes: 0

kay.one
kay.one

Reputation: 7692

Take a look at backbone-fetch-cache. It does what you want.

Upvotes: 1

Related Questions