Generate dynamic mobile web interfaces with the Dojo Toolkit

Create mobile web apps and dynamically update the application's content with data requested from a server

Using mobile devices to browse the web has become the rule. As users of mobile devices increase in number, there is a corresponding spike in the development rate of mobile applications and mobile-friendly websites. For the mobile app developer, the main concern becomes how to develop an app that can display on the majority of devices. In this article, see how the Dojo Toolkit can help you create widgets for your application that mimic the interfaces of the most popular mobile devices. The Dojo Toolkit provides a mechanism to create mobile web apps using Cascading Style Sheets, HTML, and JavaScript.

Jose Luis Lopez (jllopez@us.ibm.com), Software Engineer, IBM

Author bio photo - Jose Luis LopezJose Luis Lopez is a Software Engineer at IBM. He currently works on the IBM Workload Deployer helping customers to speed application deployment to private clouds and virtualization environments. He has worked on WebSphere Application Server Proxy, DMZ Proxy, DRS, Dynacache, and Dependency Injection for Java (CDI). He holds patents on Gaze-awareness Systems and Mobile User Interfaces.



30 August 2011

Also available in Chinese Russian Portuguese

Using a mobile device is one of the most popular ways to browse the web. As mobile device users increase, there is a call to develop more mobile applications and mobile-friendly websites. Creating native mobile applications that target different platforms (like iOS, Android, and Blackberry OS) is difficult; code that works on one device may not work on another, even for devices with the same OS implementation but different manufacturers.

With the Dojo Toolkit (dojox.mobile) you can create widgets that mimic the interface of the most popular mobile devices. In this article, you see how to use the Dojo Toolkit to create web mobile applications and dynamically update the application's content with data requested from a server. The IBM® Workload Deployer (IWD) representational state transfer (REST) application programming interface (API) is used to fetch application properties, and is also discussed in this article.

Getting started

In this article, I'll create a web mobile application called IWDMobile. The application has one simple requirement: to list and display information about data fetched from the server.

The application consists of one HTML file, IWDMobile.html, which is the core of the application. The file uses both:

  • Dojo to create widgets that mimic mobile user interfaces
  • HTTP methods to query the server

IBM Workload Deployer REST API

The IBM Workload Deployer REST API provides REST calls to manage Workload Deployer appliances. This article uses GET /resources/applicationPatterns, which is a REST call to fetch information about virtual application patterns. Virtual application patterns hold properties such as name, id, and creator.

Project structure

For this article, IWDMobile.html is placed on the public folder of a server sharing the network with the IBM Workload Deployer.

Dojo 1.7

WebSphere Application Server Feature Pack for Web 2.0 and Mobile V1.1.0

The WebSphere Application Server Feature Pack for Web 2.0 and Mobile includes the IBM Dojo 1.7 Toolkit, new mobile and rich Internet application (RIA) building blocks, and a Dojo-based diagram component. With accompanying Rational tools, the Feature Pack greatly facilitates the creation of rich web and mobile applications. In a straightforward manner, you can take WebSphere applications developed originally for desktop browsers and easily adapt and deploy them to mobile devices.

Your HTML file can access Dojo in either of two ways. It can access the Dojo available from a public content delivery network (or CDN; such as Google and AOL), or it fetch Dojo from your own website. This article refers to the features of Dojo 1.7, but since Dojo 1.7 has not yet been released and is not yet available from the public CDNs, download a copy of the latest Dojo 1.7 from the Dojo Toolkit web page and unzip it under directory/public. (See Resources for a link to download the Dojo Toolkit.)

You should have the following directory structure:

  • /public/IWDMobile.html
  • /public/dojo1.7/

Developing IWDMobile

Consider the following HTML template to start your web mobile application:

Listing 1. Sample HTML template for your app
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 
  "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta name="viewport"
          content="width=device-width,
                   initial-scale=1,
                   maximum-scale=1,
                   minimum-scale=1,
                   user-scalable=no"/>
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <title>IWDMobile</title>
    <link
         href="dojo1.7/dojox/mobile/themes/iphone/iphone.css"
         rel="stylesheet" />
    <script type="text/javascript"
            src="dojo1.7/dojo/dojo.js"
            djConfig="isDebug:true, parseOnLoad:true">
    </script>
    <script language="JavaScript" type="text/javascript">
      dojo.require("dojox.mobile.parser");
	dojo.require("dojox.mobile");
	dojo.requireIf(!dojo.isWebKit, "dojox.mobile.compat");
    </script>
  </head>
<body>
</body>
</html>

Dojo statements are part of the heading section of the HTML file. These statements load the Dojo library and the required Dojo classes to parse the information. CSS themes and mobile-specific META tags are defined too. For more information on mobile-specific META tags, see the item "Apple-specific mobile meta tags" listed in Resources below.

User interface skeleton

IWDMobile requires a view to list virtual application patterns fetched from the server. In this article, two views are used.

  • The first view will hold virtual application patterns' names.
  • The second view will hold the virtual application patterns' properties.

When a virtual application pattern's name is selected, its properties should be displayed.

Dojo provides widgets and methods that fit IWDMobile requirements. The widgets required for this application are:

  • Dojox.mobile.ScrollableView (container that represents the mobile device screen)
  • Dojox.mobile.Heading (represents a navigation bar)
  • Dojox.mobile.RoundRectList (container for items)
  • Dojox.mobile.ListItem (represents a list item)

The body section is updated to accommodate these widgets.

Listing 2. Body of the sample HTML template
<body>
    <!-- Application pattern view -->
    <div id="appPatterns" dojotype="dojox.mobile.ScrollableView">
      <h1 dojotype="dojox.mobile.Heading" label="Patterns"></h1>
    </div>

    <!-- Application pattern info view -->
    <div id="appPatternsInfo" dojotype="dojox.mobile.ScrollableView">
      <h1 dojotype="dojox.mobile.Heading"
          label="Pattern Information"
          back="Patterns"
          moveto="appPatterns"></h1>
      <ul id="patternInfoList" dojotype="dojox.mobile.RoundRectList">
	</ul>
    </div>
</body>

JavaScript functions

Two JavaScript functions are required:

  • The first function gets data from the server
  • The second function extracts properties about virtual application patterns

The first function, getApplicationPatterns(), needs to send a GET request to the server, parse the server's response, create a list container, populate the list container with list items holding virtual application pattern names, add an on-click event on each list item, and add the list container to the appPatterns view.

The second function, getPatternInfo(virtAppPatternObject), takes as argument a virtual application pattern object. The function needs to extract the properties for the virtual application pattern object, create list items holding the values of the virtual application patterns' properties, and add the list items to the patternInfoList list container.

getApplicationPatterns()

The following code segments reflect the idea behind this function.

  • Step 1: GET /resources/applicationPatterns request.
Listing 3. Getting data from the server
dojo.xhrGet({
	url :"https://iwd.server.com/resources/applicationPatterns",
	handleAs : "json",
	
	headers : {
			'X-Deployer-API-Version': '3.0',
			'Content-Type': 'application/json',
			'Accept': 'application/json' 				
			},

	load : function(response) { },
	error : function(e) { }
});
  • Step 2: Save server's response data in a new variable.
Listing 4. Saving data from the server
var sdata = response;
  • Step 3: Create a list container that will hold application names.

dojo.mobile.RoundRectList creates a new list container called applicationPatternsList.

Listing 5. Creating a list container
var appPatternListContainer = new 
dojox.mobile.RoundRectList({id:"applicationPatternsList"});
  • Step 4: Add items to the list container in Step 3 for each element in the response.

dojox.mobile.ListItem creates list item elements. Each element gets assigned a label and a moveTo property. The label is the text displayed by the list item, in this case, the virtual application pattern's name. The moveTo property tells the application which view it should open if this items gets selected. In this case, it will open the appPatternsInfo view.

addChild adds each list item to the appPatternsListItem list container.

The for-loop ensures that each list item is added to the list container.

Listing 6. Adding items to the list container
for(var i in sdata){
	
  var name = sdata[i].app_name
  var appPatternListItem = new dojox.mobile.ListItem({
					 label: name,
					 moveTo: "appPatternsInfo"
				    });

  appPatternListContainer.addChild(appPatternListItem);

}
  • Step 5: Add an on-click event on each item on the list. When an item on the list is clicked, it will display information about it on the appPatternsInfo view.

dojo.connect connects an on-click event to the list items.

dojo.hitch executes function getPatternInfo with argument sdata[i].

The for-loop ensures that each list items gets assigned an on-click event.

Listing 7. Adding on-click events
for(var i in sdata){

  dojo.connect(appPatternListItem,
               "onclick",
               dojo.hitch(null,
               getPatternInfo, sdata[i]));

}
  • Step 6: Add a list container to the appPatterns view.

dijit.byId looks up for the appPatterns view widget.

addChild adds the appPatterListContainer widget to the appPatterns view.

Listing 8. Adding a list container to the view
dijit.byId("appPatterns").addChild(appPatternListContainer);

The final code for the getApplicationPatterns JavaScript function looks like this:

Listing 9. Final code to get data from the server
function getApplicationPatterns(){
  // Send a request to the server
  dojo.xhrGet({
      url : "https://iwd.server.com/resources/applicationPatterns",
	handleAs : "json",
	headers : {
			'X-Deployer-API-Version': '3.0',
			'Content-Type': 'application/json',
			'Accept': 'application/json'
								
			},

	load : function(response) {
	    // Server responds with information in json format
          var sdata = response;

	    // Create the list container that will hold application names
	    var appPatternListContainer = new  
          dojox.mobile.RoundRectList({id:"applicationPatternsList"});
						
          // Add a new item to the list container for each element
	    for (var i in sdata){
					
		  // Create and populate the list container (app names)
		  var name = sdata[i].app_name
		  var appPatternListItem = new dojox.mobile.ListItem({
							label: name,
							moveTo: "appPatternsInfo"});

		  // Add the newly created item to the list container
		  appPatternListContainer.addChild(appPatternListItem);

              // Attach an "onclick" event for each item on the list.   
              // When the item is clicked, it will display information
              // about it on a new view (in this case appPatternsInfo)
		  dojo.connect(appPatternListItem,
                           "onclick",
                           dojo.hitch(null,  
                           getPatternInfo, sdata[i]));
						
		}
            
            // Add list container to the appPatterns view
		dijit.byId("appPatterns").addChild(appPatternListContainer);

	},
	error : function(e) {}
  });
}

getPatternInfo(virtAppPatternObject)

The following code segments reflect the idea behind this function.

  • Step 1: Clear list container.

destroyDescendants destroys the children and descendants of the specified widget. You want to make sure to start clean and remove any data previously stored in this DOM element.

Listing 10. Clearing the list container
dijit.byId("patternInfoList").destroyDescendants();
  • Step 2: Create a list of virtual application pattern properties.
Listing 11. Creating a list of virtual application pattern properties
var listItemLabels= ["Application name",
                     "Application id",
                     "Application type",
                     "Content MD5",
                     "Content type",
                     "Creation time",
                     "Creator",
                     "Last modified",
                     "Last modifier",
                     "Collection"];
  • Step 3: Get property values from the virtual application pattern object.
Listing 12. Getting property values from the virtual application pattern object
var listItemInfo = [virtAppPatternObject.app_name,
			  virtAppPatternObject.app_id,
			  virtAppPatternObject.app_type,
			  virtAppPatternObject.content_md5,
			  virtAppPatternObject.content_type,
			  virtAppPatternObject.create_time,
			  virtAppPatternObject.creator,
 			  virtAppPatternObject.last_modified,
			  virtAppPatternObject.last_modifier,
			  virtAppPatternObject.Collection];
  • Step 4: Create list items and add them to the patternInfoList container.

dijit.byId looks up for the patternInfoList view widget.

dojox.mobile.ListItem creates list item elements. Each element gets assigned a label and a rightText property. The label is the text displayed to the left of the list item, in this case, properties' names. The rightText property is the text displayed to the right of the list item, in this case, properties' values.

addChild adds the list items to the patternInfoList view.

Listing 13. Adding list items to the container
for(var j in listItemLabels){

  // Populate list container with application properties and values
  var list = dijit.byId("patternInfoList");
  var appPatternInfo = new dojox.mobile.ListItem({
      				label: listItemLabels[j] ,
	      			rightText: listItemInfo[j]
				});
  list.addChild(appPatternInfo);
}

The final code for the getPatternInfo(virtAppPatternObject) JavaScript function looks like this:

Listing 14. Final code to extract properties about virtual application patterns
function getPatternInfo(virtAppPatternObject){

  // Clear list container before attaching information to it.
  dijit.byId("patternInfoList").destroyDescendants();  

  // List of application's information
  var listItemLabels= ["Application name",
                       "Application id",
                       "Application type",
                       "Content MD5",
                       "Content type",
                       "Creation time",
                       "Creator",
                       "Last modified",
                       "Last modifier",
                       "Collection"];
		
  // List of application's values
  var listItemInfo = [virtAppPatternObject.app_name,
			    virtAppPatternObject.app_id,
			    virtAppPatternObject.app_type,
			    virtAppPatternObject.content_md5,
		          virtAppPatternObject.content_type,
			    virtAppPatternObject.create_time,
			    virtAppPatternObject.creator,
			    virtAppPatternObject.last_modified,
	     		    virtAppPatternObject.last_modifier,
	                virtAppPatternObject.Collection];
				
  // Create and populate application's information
  for(var j in listItemLabels){

    // Populate list container with application properties and values
    var list = dijit.byId("patternInfoList");
    var appPatternInfo = new dojox.mobile.ListItem({
					label: listItemLabels[j] ,
					rightText: listItemInfo[j]
				});
    list.addChild(appPatternInfo);
  }
}

IWDMobile.html

As mentioned earlier, IWDMobile.html is the core of the application. It holds the HTML code, the Dojo statements, and the JavaScript classes required to create the IWDMobile application. You can download the final version of IWDMobile.html.


Demonstration

Open the IWDMobile.html file via its URL. For example, https://iwd.server.com/IWDMobile.html

Figure 1 shows the initial view, the patterns view. This view lists virtual application pattern names. Clicking on any of the items listed redirects to the pattern information view showing detailed information about the item selected.

Figure 1. Patterns view
Patterns view listing virtual application pattern names

Figure 2 shows detailed information about the virtual application pattern "Blank application."

Figure 2. Pattern information view
Pattern information view showing details about a particular virtual application pattern

Conclusion

In this article, you've seen how to use the Dojo Toolkit to create a web mobile application that mimics mobile user interfaces. You've seen how to dynamically update the application's content with data requested from the server. The possibilities are endless. Now it's up to you to decide how your application should behave. Good luck!

Acknowledgments

Thanks to Andy Dingsor and Yoshiroh Kamiyama for their feedback during the writing of this article.


Download

DescriptionNameSize
Sample HTML file for this articleIWDMobile.zip2KB

Resources

Learn

Get products and technologies

  • Download the latest Dojo 1.7 from the Dojo Toolkit web page.
  • IBM Workload Deployer lets you extend smart SOA middleware and services into a private cloud.
  • IBM WebSphere Application Server Feature Pack for Web 2.0 and Mobile includes the IBM Dojo 1.7 Toolkit, new mobile and rich Internet application (RIA) building blocks, and a Dojo-based diagram component. With accompanying Rational tools, the Feature Pack helps you take WebSphere applications developed originally for desktop browsers and adapt and deploy them to mobile devices. Learn more.
  • Evaluate IBM products in the way that suits you best: Download a product trial, try a product online, use a product in a cloud environment, or spend a few hours in the SOA Sandbox learning how to implement Service Oriented Architecture efficiently.

Discuss

  • Get involved in the My developerWorks community. Connect with other developerWorks users while exploring the developer-driven blogs, forums, groups, and wikis.

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into Mobile development on developerWorks


  • Bluemix Developers Community

    Get samples, articles, product docs, and community resources to help build, deploy, and manage your cloud apps.

  • Mobile weekly

    Innovations in tools and technologies for mobile development.

  • DevOps Services

    Software development in the cloud. Register today to create a project.

  • IBM evaluation software

    Evaluate IBM software and solutions, and transform challenges into opportunities.

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Mobile development, Web development, Open source, WebSphere
ArticleID=754968
ArticleTitle=Generate dynamic mobile web interfaces with the Dojo Toolkit
publish-date=08302011