Wednesday, October 30, 2013

The Best PhoneGap Architecture - (4)

Enjoy the art of the coding...

4. Android backbutton handlers

As I know, many PhoneGap APP’s don’t handle android backbutton event. For example, the ones built with jQuery Mobile. When a user taps the backbutton on the android device, the APP just goes back to the previous page, and if no previous page found, the APP exists without a message.
This is absolutely not acceptable for professional PhoneGap developers. Because many pages cannot simply go back, and there should be customizable handlers to handle backbutton event on each page.
Now I’m going to show you how our architecture lets you handle the backbutton so easily.
Firstly, nova.application has an array property named histories that stores all pages except for the index.html. And then, each page (inherited from nova.Page) has an array of backbuttonHandlers. When you press backbutton on the page while the array is empty, the APP will automatically goes back to previous page if there are any in the histories.
You can clear and set nova.application.histories as you wish.
You can go back to a specified page by putting a parameter to nova.application.goback(urlUntil).
You can handle custom backbutton event easily for each page, something like:
Normally, backbutton is widely used on android phones in cases of: remove notification, cancel dialog, cancel progressing bar, etc.
If the handler is not ever needed, then you need to call this.backbuttonHandlers.pop();

nova.application.currentPage

Another property of nova.application. You can access to this object anywhere. It can be used to handle backbutton out of the page definition, instead, can be in helper methods, ect.

Nova.Page.isBackbuttonDisabled

This issued to disable the backbutton on the current page. If it’s set to true, no backbutton handlers will execute. You will find it useful in some situations.

How to test backbutton handler in web browser?

It’s really simple.
Suppose you are using Google Chrome. In the console, enter “cordova.mock.triggerBackbutton()”. It mocks a backbutton event is triggered. You can trigger other events by calling “cordova.mock.trigger(‘menubutton’)”. Of course, you need to using cordova.mock.js instead of cordova.js when testing on web browsers.
You can read another post on how the mock framework works here.

No comments:

Post a Comment