I’m trying to build an mobile application using backbone.js that will:
- Load a list of items from the server on its first run
- Commit these to Local Storage (I’m using backbone-localstorage.js)
- Be able to save list items as favorites, saving this in local storage
The app will never commit changes of the data to the server but only work with the local storage.
I’m loading the data from the server manually and populate the collection, it all works fine only that I can’t transfer the data to local storage.
I’m banging my head against the wall trying to get this to work. Any ideas of how to solve this is highly appreciated. All examples I’ve seen either commits to the server or is pure local storage.
A little example code would be useful.
I’m not sure how you’re loading a list of items from the server on the first run, if you’ve gotten the local storage working, but, this is the way I’d probably put it together.
The VERY EASIEST way to do this, if you never need to go back to the server to refresh any models during the app’s run, is to simply deliver the models from the server embedded in the app, and load them when you create your collection:
For more info, see Bootstrapping in the Backbone Docs.
If you need to, over the course of the app’s run, refresh from the server periodically, then..
Use backbone-localstorage is as, with a single change. Which means that its going to override the sync method and any normal “fetch”, “save”, etc. functions will be manipulating local storage. The change would be to copy the original Backbone.Sync to a new function called something like Backbone.ServerSync before replacing Backbone.Sync with the LocalStorage version. This preserves the REST sync.
Then, I would extend Backbone.Collection with a new function which is used to fetch data from the server, using your Backbone.ServerSync function.
It doesn’t look like backbone-localstorage interferes with the URL properties of collections, so you should be able to do this pretty easily.
This new collection function, called, say, serverfetch for clarity would more or less be a clone of fetch, but using your Backbone.ServerSync method instead of Backbone.Sync.
After it gets the response from the server and parses it, it will call add for each model which should commit them to local storage.