Creating the app code
Welcome back, last time in my previous post we created our web-sql-storage.js object which enables us to abstract storage methods away from our main app meaning that, should in the future we decide to use a different storage mechanism we can do so without rewriting our main app.js file.
Our main app.js file will bind any events, talk to the WebSqlDB object and handle any DOM manipulation. So, lets get started by declaring the app object and adding our initialize method which will instantiate our WebSqlDB.
Next, lets add our findAll method which will grab all the todos from the store and build up the HTML and insert it into the DOM.
Now lets add our findById method for finding getting individual todos.
It’s worth pointing out here that rather than passing ID’s in the URL we’re going to be appending them to elements with a data-* attribute, getting them on certain events and passing them to the called method (see binding events below). Jquery mobile doesnt support the passing of params between pages via the URL (http://view.jquerymobile.com/1.3.2/dist/demos/faq/pass-query-params-to-page.html). There are third party plugins available that allow you to do this but I felt our method was cleaner.
Next we’ll add our CRUD methods.
Then we need to add in our markCompleted and markOutstanding methods.
We also need to add a small jQuery plugin to the top of the file, above the var app declaration.
$.serializeObject is a variant of the existing jQuery
$.serialize method which, instead of encoding form elements to string, converts form elements to a valid JSON object - https://github.com/hongymagic/jQuery.serializeObject. I’ve used this plugin because I find JSON much easier to work with than DOM or string manipulation.
Next we need to bind our methods to events within the initialize method. After adding these our initialize method will look like the following:
As you can see on the events triggering insert, update and delete, by using JSON.stringify and serializeObject() on the form data we end up a nice little JSON object containing our form data ready to pass to our storage methods.
Finally we need to add
to the end of our app.js file (outside of the app object) to initalize the whole app.
Our finished app.js should look like the following:
You can now run this in your browser (making sure your browser supports WebSQL and the other HTML5 features we’ve used). You can view the database by using your browser dev tools like so: