Home > Articles > Mobile Application Development & Programming

This chapter is from the book

Creating a Navigation App Project

We can create a new project using the Navigation App project template called NavigationApp. Now we can see a number of new files created. The first new file is the navigator.js file under the /js folder. There is also a new pages folder with a home subfolder. Inside the home subfolder are three more files: home.css, home.html, and home.js (see Figure 2.8).

Figure 2.8

Figure 2.8. The Navigation App project adds new files.

When using the web, we can easily add anchor tags and do a redirect to an entirely different page. However, when we simply redirect, we lose all our state. For apps, this can be bad. WinJS provides navigation functionality that helps maintain application state when moving among multiple pages inside an app.

Creating Single-Page Applications

Websites typically use either multipage navigation or single-page navigation. Websites that use single-page navigation are typically called Single Page Apps (SPAs). Multipage navigation is typical of most websites, with each hyperlink causing the entire page to be unloaded and a new page loaded. Because this is HTML, navigating to a new page with a top-level navigation causes a blank screen to appear. All state is lost unless explicitly saved with client- or server-side code. Figure 2.9 shows the multipage navigation model.

Figure 2.9

Figure 2.9. Multipage navigation unloads the existing page and loads the new page.

Single-page navigation, on the other hand, still allows for the app to be split into multiple physical page files, but when the user clicks a hyperlink, the new page content is loaded inside the main page. This way, the main page maintains all state and the new content is simply treated as dynamic data. Because the page is never unloaded, the scripts remain intact. This makes managing state easier and enables us to transition the new content with animations. For these reasons, single-page navigation is the recommended navigation model for Windows Store apps using JavaScript. See Figure 2.10.

Figure 2.10

Figure 2.10. Single-page navigation keeps the main page loaded and replaces some content with content from another page.

Understanding the WinJS Navigation Objects

Most apps need a consistent way of navigating to multiple pages and keeping track of where they are in the process. WinJS provides the Navigation object for this common need. This object exposes functions such as navigate, back, and forward. It also exposes the onbeforenavigate, onnavigating, and onnavigated events. In addition, the object exposes the following properties: canGoForward, canGoBack, history, location, and state. The WinJS.Navigation object simply maintains a stack of the URLs that the app has navigated to.

The next piece of the puzzle that WinJS provides is the pages themselves. The WinJS.UI.Pages.PageControl object enables us to define a modular unit of JavaScript, HTML, and CSS. We can navigate to this unit or use it as a custom WinJS control. We saw the built-in WinJS ViewBox control being used earlier. The NavigationApp project gives an example of this modular unit. In the /pages folder is a /home subfolder that contains the .html, .css, and .js files that make up the home PageControl. We cover how this PageControl is defined in the code shortly. We also look at WinJS built-in controls in detail during Hour3.

Even though WinJS provides these objects, we would need to write a lot of code to have our single-page apps navigate correctly. Fortunately, the Navigation App project template solves this problem with the navigator.js file. The navigator.js code uses the WinJS.Navigation object and the WinJS.UI.Pages object to accomplish the common needs of single-page applications.

Working with the PageControlNavigator

The navigator.js exposes a PageControlNavigator namespace. PageControlNavigator is not part of WinJS; it is boilerplate code that the Visual Studio project template adds to the project. We can thus customize it as needed. In this book, we use it as is because it meets our needs nicely.

The navigator.js code creates a WinJS control called PageControlNavigator. Again, this control is not part of WinJS, but our app code (albeit, boilerplate code) is creating this new control on-the-fly and making it a part of the WinJS namespace. This is the power of a dynamic language such as JavaScript. This means that any of our app codes can create a WinJS control. We cover how to create our own control during Hour 4, “Creating WinJS Namespaces, Classes, and Custom Controls.”

To see how the PageControlNavigator control is used, we can look at the default.html file:

<div id="contenthost" data-win-control="Application.PageControlNavigator"
                      data-win-options="{home: '/pages/home/home.html'}"></div>

This div has an id of contenthost. The actual id value is not important and can be anything. By using the data-win-control, we instantiate the Application.PageControlNavigator control. With the data-win-options attribute (another custom data attribute that Microsoft provides), we can pass parameters to the control’s constructor. It takes a JavaScript Object Literal. For the PageControlNavigator, we need to set the home property to the actual URL of the page we want to load inside default.html. If the control took more than one parameter, we would separate them with a comma just as in any JavaScript Object Literal.

Examining the Home Page Control

Listing 2.1 contains the markup of /pages/home/home.html. This page control is loaded into the default.html because we passed this page to the home parameter of the Application.PageControlNavigator constructor.

Listing 2.1. The Markup Portion of the Home Page Control

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>homePage</title>
     <!-- WinJS references -->
    <link href="//Microsoft.WinJS.1.0/css/ui-dark.css" rel="stylesheet" />
    <script src="//Microsoft.WinJS.1.0/js/base.js"></script>
    <script src="//Microsoft.WinJS.1.0/js/ui.js"></script>
    <link href="/css/default.css" rel="stylesheet" />
    <link href="/pages/home/home.css" rel="stylesheet" />
    <script src="/pages/home/home.js"></script>
</head>
<body>
    <!-- The content that will be loaded and displayed. -->
    <div class="fragment homepage">
        <header aria-label="Header content" role="banner">
            <button class="win-backbutton" aria-label="Back" disabled
                    type="button"></button>
            <h1 class="titlearea win-type-ellipsis">
                <span class="pagetitle">Welcome to NavigationApp!</span>
            </h1>
        </header>
        <section aria-label="Main content" role="main">
            <p>Content goes here.</p>
        </section>
    </div>
</body>
</html>

The code in Listing 2.1 is more than just a fragment of markup—it is an entire page! However, this is not a problem. Any scripts that our fragments want to load that are already loaded are ignored. This means that the WinJS script files (base.js and ui.js) and the default.js are loaded when the default.html page loads. Because default brings in content from the home.html file, home.js is also loaded. Both base.js and ui.js are ignored because they were already loaded by default.html. Having all the scripts and styles in the page controls is beneficial because it enables us to load the page control in Blend for Visual Studio and see exactly what it will look like. We talk about Blend for Visual Studio during Hour 5.

The JavaScript portion of the home page control is a self-executing anonymous function that registers itself with WinJS as a page control. This is done through the WinJS.UI.Pages.define function:

(function () {
    "use strict";

    WinJS.UI.Pages.define("/pages/home/home.html", {
        // This function is called whenever a user navigates to this page. It
        // populates the page elements with the app's data.
        ready: function (element, options) {
            // TODO: Initialize the page here.
        }
    });
})();

The define function takes in the id of the page control (the URL) as the first parameter and takes an object literal as the second parameter. The object literal contains the page control’s functions. Take a minute and let this code sink in. We are telling WinJS that we want to define a page control. We give it an id (the relative URL of the markup) and then tell it to create some functions on-the-fly that we want it to add to the page control. Dynamic languages aren’t half bad! (Remind me I said that when we get to the debugging portion of the book in Hour 7, “Debugging, Securing, and Measuring Our Apps’ Performance.”)

If WinJS.UI.Pages.define is called multiple times with the same URL, the members are added to the existing members. If a member already exists, the last one defined replaces the one already present.

The last part of the page control is the style sheet. The contents of home.css are as follows:

.homepage section[role=main] {
    margin-left: 120px;
}

@media screen and (-ms-view-state: snapped) {
    .homepage section[role=main] {
        margin-left: 20px;
    }
}


@media screen and (-ms-view-state: portrait) {
    .homepage section[role=main] {
        margin-left: 100px;
    }
}

This is standard CSS using the attribute selector to style the section content of the homepage class. The content is simply being spaced 120 pixels from the left. This is the correct positioning for Microsoft design style content. We discuss this more during Hour 5. The last two CSS rules are inside media queries (@media), which we discuss during Hour 13.

We can run the application and see a single page where the content was loaded from the home page. Figure 2.11 shows the result (after changing the style of default.html and home.html to use ui-light.css instead of ui-dark.css).

Figure 2.11

Figure 2.11. The NavigationApp with the ui-light style sheet applied.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020