Using Backbone.js models with cookies and localStorage instead of REST

One of the beautiful things about Backbone.js is that its models come ready for REST right out of the box. There are many cases though, like making a 100% client-side application, in which you’d like to use alternative ways of getting and storing data. Not much of a problem. All you have to do is override the default fetch, save and destroy methods to your liking. Below is an example of a modal which uses localStorage (require.js is also being used hence the define and return).

define(['backbone'], function(Backbone){

    return Backbone.Model.extend({
        initialize: function() {
				this.fetch();
                this.on('change', this.save, this);
			},

        fetch: function() {
            console.log("===== FETCH FIRED LOADING LOCAL STORAGE ====");
            this.set(JSON.parse(localStorage.getItem(this.id)));
        },

        save: function(attributes) {
            console.log("===== CHANGE FIRED SAVING LOCAL STORAGE ====");
            localStorage.setItem(this.id, JSON.stringify(this.toJSON()));
        },

        destroy: function(options) {
            localStorage.removeItem(this.id);
        },

        isEmpty: function() {
            return (_.size(this.attributes) <= 1); // just 'id'
        }
    })
});

If you wanted to change this to write to a cookie instead of localStorage, because cookies go to the server with each request and localStorage doesn’t, simply change the highlighted lines to these:

 

define('models/cookie_model',['backbone', 'jqueryCookie'], function(Backbone){
this.set(JSON.parse($.cookie(this.id)));
$.cookie(this.id, JSON.stringify(this.toJSON()));
$.removeCookie(this.id);

Notice, here we are using Require.js to import the jQuery Cookie plugin for convenience.

After this is done, if you’d like a certain model in your Backbone app to use a cookie or localStorage CRUD methods instead of RESTful ones, simple extend this model and use it as a normal Backbone method from then on.

define(['backbone', 'models/localStorage_model'], function(Backbone, localStorageModel){

    return localStorageModel.extend({
        defaults : {
            //whatever defaults you need.
        },
        validate: {
           //whatever you need to validate
        }
    });
});

After this you are able to use the model.get and model.set normally and typically this will fire the change method which will automatically trigger a save on the cookie or localStorage, but it does malfunction so if you see that, you can also fire it manually.

this.myRESTlessModel.get("key");
this.myRESTlessModel.set("key", "value");
this.myRESTlessModel.trigger('change');

And that’s it! Super convenient.

Comments are closed.