Get bowser navigation buttons working in your Sencha Touch application


Browser Back & Forward buttons

Problem Statement:

If your Sencha Touch application is hosted as a mobile webapp, your users would access it using the browser on their devices/mobiles. Browser has a two navigation buttons – Back and Forward. For any application running inside a browser, it is important that its state is well linked with the Back & Forward buttons so that the user is able to use them to navigate. Though the Sencha Touch framework has got the concept of History and Routes, it does not provide an in-built support to integrate your application’s state to the Back and Forward buttons.

Scope of the article:

This article provides an example implementation and explanation browser navigation buttons handling in a Sencha Touch application using routes.

Pre-requisites: 

Sencha Touch 2.1 or higher

How to do?

Step 1: Create Sample Project:

Create a sample Sencha Touch project structure either using Sencha Cmd or using manually. (visit this blog to know how to create sample Sencha Touch application using Sencha Cmd).

1)  After creating Sencha Touch project structure, create a sample view file.

Below sample code contains a panel with container item in it which is having layout type as card. For 1st card, displaying list with a toolbar docked to top and in second card, displaying simple html content.

Sample Code:

Main.js

Ext.define('BrowserBackExample.view.Main', {
	extend: 'Ext.Panel',
	xtype:'main',
	config : {
		layout : 'fit',
		items : [{
			xtype : 'container',
			layout : 'card',
			name : 'mainpanelcard',
			activeItem : 0,
			items : [
			{
				xtype : 'list',
				itemTpl: '{listItem}',
				data: [
					{ listItem: '1st List Item' },
					{ listItem: '2nd List Item' },
					{ listItem: '3rd List Item' },
					{ listItem: '4th List Item' }
				],
				items :[{
					xtype : 'toolbar',
					title : 'Browser Back Sample',
					docked: 'top'
				}]
			},{
				xtype : 'panel',
				html : 'Welcome to 2nd card.'
			},{
				xtype : 'titlebar',
				docked :'bottom',
				items :[{
					xtype : 'wtcbutton',
					text : 'Next',
					align : 'right'
				},{
					xtype : 'wtcbutton',
					hidden : true,
					text : 'Previous',
					align : 'left'
				}]
			}]
		} ]
	}
});

2)  For title bar in above code, wtcbutton was used. It is simply a button, which handles tap events, which is common for all buttons that you user in application.

Create a button view as shown below.

Sample Code:

Button.js

Ext.define('wtc.ux.Button',{
	extend:'Ext.Button',
	alias:'widget.wtcbutton',
	initConfig:function( config ){

		Ext.apply( this.initialConfig,{
			listeners: {
				tap: function() {
					if( this.config.name ) {
						this.fireEvent('redirectonbuttontap',this);
					}
				}
			}
		});

		this.callParent( arguments );
	},
	initialize: function() {
		this.callParent(arguments);
	}
});

3)  add dependency (the button component is required in app.js)

requires: [
'wtc.ux.Button'
]

4) Now, run the application in browser. Prepared list view with a button at bottom will be displayed.

 Image

Step 2: Create Controller:

Create a controller for the application by mentioning views and refs.

 Sample Code:

Ext.define('BrowserBackExample.controller.Main',{
	extend: 'Ext.app.Controller',
	config:{
		views:['Main'],
		refs :{
		   Main : 'main',
		   mainCard:'container[name=mainpanelcard]'
		}
	},
	init : function() {	
	}
});

refs provides methods for specified view names. In above code, you can access main panel card by using this.getMainCard().

Step 3: Adding Routes:

Add routes config in controller after refs config.

routes : {
     ':nextButtonName': 'showActiveView'
}

Whenever application identifies hash(#) value in document url, if it is in http://yourprojecturl/#hashValue format, then it will call the method showActiveView.

If you add routes as

':firstHashValue/:secondHashValue': 'showAnotherView'

showAnotherView method gets called when application identifies the document url in ‘http://yourprojecturl/#hashValue/someotherValue‘ format.

Step 4: Implementing History:

1)  Whenever a button is tapped, redirectonbuttontap event gets fired. So, add a function in controller to handle that event. Add a handler for redirectonbuttontap event in controller.

Use control config for adding event handlers.

control:{
 'wtcbutton' : {
 'redirectonbuttontap' : 'handleRedirect'
}
}

 2)  Add function handleRedirect after init method.

handleRedirect : function(tappedButton) {
   var buttonName = tappedButton.config.name;
   this.getApplication().redirectTo(buttonName);
 }

In above function, redirectTo method will add the hash value to document location with passed parameter. Here parameter is button name.

3)  When button was clicked, control will come to handleRedirect method. And here, as hash value is being added to the url, it will call showActiveView method, which was registered for routes. So add a method showActiveView in the controller.

Here the logic goes.

 Sample Code:

 showActiveView : function(functionName) {
    var nextButton = Ext.ComponentQuery.query('button[name='+ functionName + ']');
    if (nextButton.length > 0) {

       nextButton = nextButton[0];
        if (this[functionName]) {

           this[functionName](nextButton);
        }
    }
 }

4)  In above code, querying for getting button using button name. If button exists, calling a function which is having button name. So, make sure that, whatever the name that you pass to the button, should have a function with that name in controller.

So,first add button names in view file and then write functions with those names in controller.

{
	xtype : 'titlebar',
	docked :'bottom',
	items :[{
			xtype : 'wtcbutton',
			name : 'switchToNextCard',
			text : 'Next',
			align : 'right'
		},{
			xtype : 'wtcbutton',
			name : 'switchToPreviousCard',
			hidden : true,
			text : 'Previous',
			align : 'left'
		}
	]
}

5)  In above code, the added button names are switchToNextCard and switchToPreviousCard.

So, add functions with above names in controller as well. Here the logic to navigate views will go.

 Sample Code:

 
switchToNextCard : function(button){
     this.getMainCard().setActiveItem(1);
     button.hide(true);
     var previousButton = this.getMainCard().down('button[name=switchToPreviousCard]');

     if( !Ext.isEmpty(previousButton ) ) {
         previousButton.show(true);
     }
 },
switchToPreviousCard : function(button){

   this.getMainCard().setActiveItem(0);
   var nextButton = this.getMainCard().down('button[name=switchToNextCard]');
   button.hide(true);
   if( !Ext.isEmpty(nextButton ) ) {
       nextButton.show(true);
   }
}

Step 5: Browser Navigation:

1)   Now, run the application in browser. Main view doesn’t change.

Image

2)  Tap on next button. Observe change in the hash value in url and view will display 2nd card with previous button.

 Image

3)  Now, click on browser navigation back button.

Image

After clicking,

 Image

From here, you can switch between these two views with browser back and forward buttons.

Step 6: Handling Device navigation with routes:

 The above code will also works well for device back button as well. No code changes are required.

1)  Run application in android emulator.

 Image

2)  Tap on next button.

 Image

3)  Click on android device back button.

 Image

After clicking,

 Image

Summary

As part of this article you came to know about the steps to implement browser’s backward  / forward button and hardware back button ( for example on android, BB and windows phone) on Sencha Touch based application. Since Sencha Touch allows you to build your app once and run it on all the devices, it becomes very important to handle this kind of thing to ensure that the user gets the native experience. I hope you have enjoyed reading this article and you are able to apply this learning to meet your business need.

At Walking Tree we practice and recommend Sencha Products like ExtJS and Sencha Touch to build amazing web / touch apps. In case you are looking for training or professional assistance, contact us by visiting our website.

References:

  1. http://docs.sencha.com/touch/2-1/touch-build/examples/kitchensink/index.html
  2. http://docs.sencha.com/touch/2-1/#!/guide/history_support
  3. https://github.com/walkingtree/sample-projects/tree/master/SenchaTouch/BrowserBackHandlingExample
Tagged with: , , , , , ,
Posted in Sencha Touch

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

We Have Moved Our Blog!

We have moved our blog to our company site. Check out https://walkingtree.tech/index.php/blog for all latest blogs.

Sencha Select Partner Sencha Training Partner
Xamarin Authorized Partner
Do More. With Sencha.

Recent Publication
%d bloggers like this: