underscore666
underscore666

Reputation: 1739

How to make a cache/memorizer in BackboneModel

Let's suppose I have a View which can make model.fetch() and then a request to the server.

I would like to implement:
1) A checker able to memorise the result
2) refresh the result (making the request to the server) only if the last request to the server is older than ten minutes.

What should I do?
Is there already a piece of code to make that?

define([], function() {

    var MyModel = Backbone.Model.extend({

    url: function () {
        return "http://localhost/restapi/model/";
    },

    fetch () {
        if(diffTime > 10minutes) {
            // make request to the server
        }
        else {
            // return memo
        }
    }    

    });

});

Upvotes: 1

Views: 703

Answers (3)

Mosselman
Mosselman

Reputation: 1748

I have found https://github.com/Ask11/backbone.offline to work really well for me.

The only vice is that it uses localStorage, you could also opt for more support by going with rewriting bits and pieces for use with amplify.store http://amplifyjs.com/api/store/.

Upvotes: 0

Parth Thakkar
Parth Thakkar

Reputation: 5475

As codemonkey said, localstorage would be a good option. But if you don't want to use a library for that, you can use this class to extend those models who require the cache functionality.

var CachedModel = Backbone.Model.extend({

    lastFetch: null,    // millisec.
    cache: { }
    fetch: function () {
        if(!this.lastFetch || (lastFetch - Date.now() > 10*60*1000) {
            // make request to the server
        }
        else {
            // return this.cache
        }
    }    

});

Upvotes: 1

codemonkey
codemonkey

Reputation: 5267

You need to override the Backbone.sync method http://documentcloud.github.com/backbone/#Sync.

This code does the saving to local storage to implement a cache http://documentcloud.github.com/backbone/docs/backbone-localstorage.html.

It is fairly simple to add some logic in the "read" case to fetch from the server if the data is older than 10 minutes.

Upvotes: 3

Related Questions