Click here for a PhoneGap Calculator
Here is an easy to get your head around jQuery Mobile (JQM) project, a simple calculator. I like this project because it helps to break want-to-be web app program out of the web site mentality. The entire app consist of a single page and about 200 lines of code. Let’s begin our explanation with the Kernel which is near the beginning of the file app.js.
The Page Code
Next comes the page’s code in RocknCoder.Pages.calculator. We use an object literal to hold all of the pages code. At some point in the future I will be changing this code to use a function not an object literal, but I have been doing for so long like this the habit is hard to break. A better implementation would be to do something like a “Revealing Module Pattern”, which would also give us the ability to hide our local variables.
In the page’s code we handle three events: pageinit, pageshow, and pagehide. Any event which is not defined is not called by the Kernel. The first event handler, pageinit, is the JQM’s equivalent to jQuery’s document ready event. This is the place to do any page level initialization code. Here we initialize our Android address bar hider. The second event, pageshow, is called after JQM has rendered the page. In this handler we initialize the calculator, the poorly named RocknCoder.Display and hook all of the calculator’s keys. The final event is pagehide, which we use to unhook the events. Truth be told, this event will probably never be called since there is only one page and JQM will have no page to switch to and therefore no need to hide the current page.
The meat of the calculator is in RocknCoder.Display. I am not going to explain its function other than to say it is a very simple calculator. We could have created a more robust calculator by using the Command Pattern. Then we could have been able to have features like undo and a much cleaner separation of concerns. But then it would not have been so light in code.
Next week I will turn the calculator into a PhoneGap project and show how to get it to run on iPhone, Android, and Windows Phone 7.
Complete Source Code
https://gist.github.com/2702298.js?file=app.js https://gist.github.com/2702294.js?file=index.htm https://gist.github.com/2702315.js?file=hideAddressBar.js