You can download/clone the project here or view a live demo
Swapping our storage method
Hi, welcome back. In my last post we finished our Simple Todo app using jQuery mobile and WebSql, this time we’re going to replace WebSQL with Local Storage. You may remember that we separated our storage method from our app.js. This makes changing the storage method much easier as we only need to swap the web-sql-storage.js for our new local-storage.js file (which we’re going to create below) and change a few lines of code in our app.js and html files.
So, rather than talking you though each line I’ve put the new localstorage.js file in the above project (github links at the top of the post) and in the below gist. I’ve commented the code enough to explain whats happening at each stage.
The main things to note are:
- All callbacks are wrapped in a CallDelay method which simulate async calls. This is done to provide a consistent interface with storage methods like WebSQL and server side ajax calls
- The todos are being stored as a array of objects within a LocalStorage item
- When CRUD operations are being run, we first have to get the JSON from the LocalStroage item and then make our changes to it before saving it back
- The same data is being passed back to app.js as it received from the web-sql-storage.js file.
Changes to app.js
With out new local-storage.js file in place we need to edit the following line within app.js:
Changes to HTML
All thats left is to include our new file within our HTML, replacing the web-sql-storage.js script:
You can view the JSON contained within Local Storage by using your browsers dev tools.