Technology

Fast caching in Backbone.js using localStorage

Posted by Pixafy Team

backbone-js

I recently attended GothamJS, the New York City JavaScript conference, with my Pixafy colleagues. At the event, many interesting technologies were introduced by speakers on topics such as AngularJS, Backbone.js for mobile, and CSS3 Animation. Among these technologies, Backbone.js for mobile caught my attention. This is a useful technique for Backbone developers to build large scale web applications.

[series_block]

This post is part of a series on topics covered at GothamJS:

[/series_block]

During this session, JavaScript and Backbone expert Nick Gauthier introduced using Backbone.js for mobile web applications by using localStorage for caching the model instead of sending requests to the server for all communications with the server. After checking out a couple of his online tutorials, I have a better understand of how the caching works in Backbone. Before you start using Backbone localStorage, backbone-localStorage.js is needed.

Once you have everything set up, let’s take a look at the following code:

Models.foo =Backbone.Model.extend({})
Models.foos =Backbone.Collection.extend({
localStorage: new Store(‘foos’);
})

The line of code localStorage: new Store (‘foos’); equal url: ‘some url’ allows the Backbone model to make RESTful requests with local storage instead of the server. That means you can call Models.foos.fetch() ,Models.foos.save() and Models.foos.destroy() to deal with data in local storage. This could be a very useful technique for web applications to allow users to use both online and offline.

Before going that route, I do think that there are some important pros and cons to consider:

Pros:

  • Allow web applications to be used offline
  • Reduce requests with server
  • Fast response

Cons:

  • User could lose all data if s/he accidentally clears local storage
    For instance, if a user thought that the data had been sent to the server but it had not, s/he could lost all that information.
  • Might be out of sync with the server
  • Not easy to handle synchronization with server

Overall, I think this is very nice technique for web applications. It could improve user experience by providing fast response times when applications need to do a lot of data exchanges with the server, submitting the final changes at the end. One scenario is an educational application that allows users to take exams on a mobile device or tablet while they are riding the subway and without Internet access. The users can submit their exam responses later when they have Internet again on their device. In addition, the users will not have long wait times, which improves user experience.

For a demo, please visit https://github.com/ngauthier/intro-to-backbone-js.

We hope you found this post on Backbone.js and localStorage informative. If you have any questions or comments, please leave a note below, or tweet us @Pixafy.