As you may know Android has a back button – present as a software back button or in older devices as a capacitive button on the device itself. The question is how to hook into it and get your views to change in Sencha Touch. Sure, Sencha walks you through Routes and such, but all I want is something simple, and this technique is just that, simple and easy to understand.

This approach uses the browser’s history object and updates it with a hash comprised of the current panel’s id. As you navigate about your app the hash is updated as desired. When the user taps Android’s back button the history object’s back() method is fired. Hash changes don’t cause a page reload so your app doesn’t reload either. After firing the back() method we wait a few milliseconds and then fire our own function to update the view based on the current hash.

This works great for an app that is comprised of a single container whose children are the panels that you want to view. More complex structures would require that you get into Sencha Touch’s Routing mechanism (and to be honest, you *should* be using routes).

One Level of Navigation within a single container

Lets review a scenario that is conducive to implementing simple back button functionality – an app built with the following structure:

back_history_structure_1

As you can see this is a very simple app – a single container with one level of children.

To begin lets add 2 custom methods to our application. Start Architect, and click on the “launch” node within the Project inspector and paste the following into the code view:

Ext.define('MyApp.appHistory', {
    statics: {
        goBack: function(){
            if (location.hash.length != 0){
                var hash = location.hash.substring(1);
	            Ext.getCmp('initialView').setActiveItem(Ext.getCmp(hash));
            } else {
                MyApp.Utilities.addHashToUrl();                                      
            }
        },
        addHashToUrl: function(){
            var id = Ext.getCmp('initialView').getActiveItem().id;
            var loc = location.href;
            var hash = location.hash.substring(1);
            var root = null;

            if (loc.indexOf('#') != -1){
                root = loc.split('#');
                location.href = root[0] + '#' + id;
            } else if (id != hash){
                location.href = loc + '#' + id;
            }
        }
    }
});


Ext.define('MyApp.MyView', {
    extends: 'Ext.panel.Panel',
    requires: ['MyApp.appHistory'],
    initComponent: function() {
        MyApp.appHistory.goBack();
    }
});

Ext.define('MyApp.MyView', {
    extends: 'Ext.panel.Panel',
    requires: ['MyApp.appHistory'],
    initComponent: function() {
        MyApp.appHistory.addHashToUrl();
    }
});

What we’ve done here is add an “appHistory” object to our “MyApp” app (“MyApp” is the default namespace that Architect gives your app) and exposed two methods:

  • MyApp.appHistory.goBack() – this handles the back functionality for the app.
  • MyApp.appHistory.addHashToUrl() – this updates the location hash.

Finally we need to hook into PhoneGap’s “backbutton” event. We do so by adding an event listener within our index.html. You’ll notice the typical “deviceready” event listener wrapped by the document’s “load” listener which ensures that our code runs only when the DOM has been loaded and the device is ready:

window.addEventListener('load',function(){
	document.addEventListener('deviceready',function(e){
		// setup the back button
		document.addEventListener('backbutton', function(e){
			history.back() // go back in the browser's history
			setTimeout(function(){
				MyApp.appHistory.goBack(); // update the view against the current hash
			},100);
			return false;
		}, false);
	});
});

Looking at the above we can see that when the “backbutton” event fires we go back in the browser history then we wait a short bit of time to ensure that the location has been updated before following with the call to navigate back within the app.

The last thing to do is to update the hash from within your Sencha application. I’ve placed the ” MyApp.Utilities.addHashToUrl();” method call within my controller’s onButtonTap event which is sufficient for this example.

This is a good starting point – you’ll of course need to modify per your specific needs, have fun!