JavaScript project templates for Windows Store apps

39 out of 59 rated this helpful - Rate this topic

This topic provides in-depth info about the project templates for Windows Store apps built for Windows using JavaScript. In addition to a brief summary of each template, implementation details about the navigation model, data model, handling of view state, and other details are provided. Many of these implementation details apply to more than one template.

For info about Visual Studio and Blend templates for other languages, see Jump start your app using templates (C#/VB/C++).

Grid project template for Windows Store apps

The Grid App template is a great way to start a Windows Store app that you can customize to enable users to browse through categories to find content in which they will want to fully immerse themselves. Examples include shopping apps, news apps, and photo or video apps. This template uses the JavaScript navigation model that is recommended for Windows Store apps.

The Grid app defaults to a home page that shows a list of groups. A group represents a named set of items, such as a part of a virtual department store that has individual retail items. If the user selects a group, the app opens the group details page, which has a list of the items on the right side. The user can select an item from either the home page or the group details page. This opens a full-page view that shows the item details (shown here on top).

Grid Application project template

Project files for the Grid template

The Grid App template includes these HTML files:

  • default.html, which is loaded first and provides markup for the content host (where each page is loaded into the main window).
  • groupedItems.html, which is the home page. It enables the user to view the groups and items, and either select an item to navigate to the full-page item view, or a select a group label to navigate to the group details page.
  • groupDetail.html, which enables the user to view group details on the left and items on the right, and select an item to navigate to the full-page item view.
  • itemDetail.html, which is the full-page view for an item.

The template includes these JavaScript files:

  • default.js, which specifies how the app behaves when it's started.
  • groupedItems.js, which specifies behavior that's associated with the home page.
  • groupDetail.js, which specifies behavior that's associated with the group details page.
  • itemDetail.js, which specifies behavior that's associated with the full-page item view.
  • navigator.js, which implements the navigation model for the Windows Store app JavaScript templates.
  • data.js, which is the data source object that exposes the data to the rest of the app.

The template includes these CSS files:

  • default.css, which specifies CSS styles for the content host page and for the app as a whole.
  • groupedItems.css, which specifies CSS styles for the home page.
  • groupDetail.css, which specifies CSS styles for the group details page.
  • itemDetail.css, which specifies CSS styles for the full-page item view.

The Grid App template also includes the package.appxmanifest file, which describes the app package for Windows, and a PFX file that is used to sign the appxmanifest file (this file is included as a project file to support building from the command line). The template also includes several image files, like splashscreen.png for the splash screen image, and storelogo.png, which is used for Windows Store.

How the Grid template works

For more info about the Grid template implementation, see:

The topic about adding data includes an example that shows how to add dynamic data to the Grid template and bind the data to the UI.

Split project template for Windows Store apps

The Split App template is a great way to start creating a Windows Store app that you can customize to enable users to view a list of items and item details in a two-column view, where users might want to switch quickly among the items, and where the list might be updated dynamically. Examples include a news reader, a sports scores app, or an email app. This template uses the JavaScript navigation model that's recommended for Windows Store apps.

The Split app defaults to a home page that shows a list of groups. A group is a named set of items, like a news source that provides news stories. When the user selects a group by tapping or clicking it, the app opens the split-view page. The Split app pages are shown here.

Split Application project template

The split-view page displays a two-column view (or master/detail view), where the details on the right side change when the user selects items on the left side. Again, imagine a list of news stories on the left side and the actual stories on the right side.

Project files for the Split template

The Split App template includes these HTML files:

  • default.html, which is loaded first and provides markup for the content host (where each page is loaded into the main window).
  • items.html, which is the home page. It enables the user to select a group to navigate to the app's split-view page.
  • split.html, which is the split-view page. It defines two sections—one for the list of items on the left and another for the item details on the right.

The template includes these JavaScript files:

  • default.js, which specifies how the app behaves when it's started.
  • items.js, which specifies behavior that's associated with the home page.
  • split.js, which specifies behavior that's associated with the split-view page.
  • navigator.js, which implements navigation for the Windows Store app JavaScript templates.
  • data.js, which is the data-source object that exposes data to the app.

The template includes these CSS files:

  • default.css, which specifies CSS styles for the content host page and for the app as a whole.
  • items.css, which specifies CSS styles for the home page.
  • split.css, which specifies CSS styles for the split-view page.

The Split App template also includes the package.appxmanifest file, which describes the app package for Windows, and a PFX file that is used to sign the appxmanifest file (this file is included as a project file to support building from the command line). The template also includes several image files, like splashscreen.png for the splash screen image, and storelogo.png, which is used for Windows Store.

How the Split template works

For more info about the Split template implementation, see:

The topic about the adding data includes an example that shows how to add dynamic data to the Split template and bind the data to the UI.

For an example that shows how to add dynamic data and customize features of the Split template, see Create a Blog Reader.

For an example that shows how to add search to the Split template, see Adding a Search Contract item template.

Navigation project template for Windows Store apps

The Navigation App template provides basic navigation by using the navigation model recommended for Windows Store apps. The template contains only one minimal page fragment to which you can easily add more page fragments by using the Page Control item template. You can then add your own content.

The Navigation app defaults to a home page that displays a "Welcome" title, as shown here.

Navigation Application project template

Project files for the Navigation template

The Navigation App template includes these HTML files:

  • default.html, which is loaded first and provides markup for the content host (where each page is loaded into the main window).
  • home.html, which is the home page. It displays a "Welcome" title.

The template includes these JavaScript files:

  • default.js, which specifies how the app behaves when it's started.
  • home.js, which specifies behavior that's associated with the home page.
  • navigator.js, which implements the navigation model for the Windows Store app JavaScript templates.

The template includes these CSS files:

  • default.css, which specifies CSS styles for the content host page and for the app as a whole.
  • home.css, which specifies CSS styles for the home page.

The Navigation App template also includes the package.appxmanifest file, which describes the app package for Windows, and a PFX file that is used to sign the appxmanifest file (this file is included as a project file to support building from the command line). The template also includes several image files, like splashscreen.png for the splash screen image, and storelogo.png, which is used for Windows Store.

How the Navigation template works

For more info about the Navigation template implementation, see:

If you need to include special handling of view state changes in the Navigation template, you must make changes to your code. We recommend that you use the same pattern used in the Grid and Split templates, which is to implement updateLayout in the HTML pages. For more info, see Handling view state. Support for updateLayout is provided in the shared navigation model.

To add pages to the app, use the Page Control item template. For an example of adding a Page Control, see Adding a Page Control item template.

Blank project template for Windows Store apps

The Blank App template provides a minimal Windows Store app that compiles and runs, but contains no user interface controls or data. When you run an app that's based on the Blank project template, you see a black screen that contains placeholder text.

Project files for the Blank template

The Blank App template includes this HTML file:

  • default.html, which is the home page of the app.

The template includes this JavaScript file:

  • default.js, which specifies how the app behaves when it's started.

The template includes this CSS file:

  • default.css, which specifies CSS styles for the app.

The Blank App template also includes the package.appxmanifest file, which describes the app package for Windows, and a PFX file that is used to sign the appxmanifest file. The template also includes several image files, like splashscreen.png for the splash screen image, and storelogo.png, which is used for Windows Store.

How the Blank template works

For more info about the Blank template implementation, see:

The overall behavior and appearance of the Blank template is created by a CSS style sheet: ui-dark.css. You can change this reference in your HTML pages to ui-light.css. For more info, see CSS styles.

Fixed Layout project template for Windows Store apps

The Fixed Layout App template provides a minimal Windows Store app that's the same as an app created in the Blank App template except that its content is meant for a fixed viewport. We recommend this template for most game apps that are created in JavaScript.

When you run an app that's based on the Fixed Layout project template, you see a black screen that contains placeholder text.

Project files for the Fixed Layout template

The Fixed Layout App template includes this HTML file:

  • default.html, which is the home page of the app.

The template includes this JavaScript file:

  • default.js, which specifies how the app behaves when it's started.

The template includes this CSS file:

  • default.css, which specifies CSS styles for the app.

The Fixed Layout App template also includes the package.appxmanifest file, which describes the app package for Windows, and a PFX file that is used to sign the appxmanifest file. The template also includes several image files, like splashscreen.png for the splash screen image, and storelogo.png, which is used for Windows Store.

How the Fixed Layout template works

For more info about the Fixed Layout template implementation, see:

The size of a Fixed Layout app is scaled to conform to the display area. The template uses a ViewBox control for scaling. For example, if you choose a resolution of 768 x 1024 for your app, but the device running the app doesn't have a 768 x 1024 display area available, the app is scaled up or down to make sure that its fixed-layout viewport appears to the user.

The overall behavior and appearance of the Fixed Layout template is created by a CSS style sheet: ui-dark.css. You can change this reference in your HTML pages to ui-light.css. For more info, see CSS styles.

Common coding features

The following features are common to all of the project templates:

  • Each JavaScript file wraps code in a self-executing anonymous function, as follows:
    
    (function () {
        // . . .
    })();
    
    

    Members added inside the anonymous function are private, but you can make them public using the WinJS.Namespace.define function. The use of the anonymous function changes the way you need to write some code, such as when adding your own event handlers. For more info, see Coding basic apps.

  • Each JavaScript file specifies the use of strict mode with the "use strict" statement. For more info, see Strict Mode in the JavaScript Language Reference.
  • Default.js includes a call WinJS.Binding.optimizeBindingReferences. This function helps prevent memory leaks when declarative binding is used in an app, as is common in the templates.
  • Strict declarative processing is always on. You must use WinJS.Utilities.markSupportedForProcessing to specify that a function is allowed to use declarative processing.

XML Documentation Comments are used in a few places in the JavaScript files to provide a more complete IntelliSense experience. For more info, see JavaScript IntelliSense.

App lifecycle

The implementation of the app lifecycle is the same for all of the JavaScript project templates for Windows Store apps. The app lifecycle begins when the app starts and ends when the app is closed. The project templates include a generic pattern for managing the app lifecycle. When you create an app that's based on a project template, you might need to include code to handle additional scenarios, such as handling data when the app is suspended or terminated.

The default.html file is set as the start page for each template. The corresponding JavaScript file for default.html includes the following call to WinJS.Application.start, which starts dispatching app events.


var app = WinJS.Application;
// . . .
app.start();

The best place to add code related to app lifecycle management is in default.js. The implementation of default.js is the same for all of the project templates. This file includes code to handle the Windows Library for JavaScriptonactivated event. This event is raised when Windows Runtime activation occurs. The code in the onactivated event handler checks whether the app was started from the Windows Start screen and calls WinJS.UI.processAll. The processAll function loads all the controls that include the data-win-control attribute in the DIV element of the control. Here's the code that contains the processAll function.



app.addEventListener("activated", function (args) {
    if (args.detail.kind === activation.ActivationKind.launch) {
        if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
            // . . .
        } else {
            // . . .
        }
        // . . .
        }
        args.setPromise(WinJS.UI.processAll().then(function () {
            // The code in this section navigates to the current page, if one
            // is set, or the home page if a current page is not set.
            // . . .
        }));
    }
});

If you have code that needs to run when the app sets up its initial state, you should include that code in the handler for the Windows Library for JavaScriptonactivated event. You might also need to include additional code if the app has been reactivated after being suspended. Add this code where indicated by the code comments.



if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
    // TODO: This application has been newly launched. Initialize
    // your application here.
} else {
    // TODO: This application has been reactivated from suspension.
    // Restore application state here.
}


As mentioned earlier, the templates don't include code to handle suspending the app. To handle this app state in your code, you can add code to the Windows Library for JavaScriptoncheckpoint event handler, shown here in default.js, or add code to register for the Windows Runtime suspending event (which calls oncheckpoint).


app.oncheckpoint = function (args) {
    // TODO: This application is about to be suspended. Save any state
    // that needs to persist across suspensions here. If you need to 
    // complete an asynchronous operation before your application is 
    // suspended, call args.setPromise().
    app.sessionState.history = nav.history;
};

You can use Windows Library for JavaScript or Windows Runtime events, or a combination of both, to manage the app lifecycle. However, Windows Library for JavaScript events and functions are sufficient for most apps. For more info, see How to suspend an app and How to resume an app.

Here are a few of the Windows Library for JavaScript events and functions related to the app lifecycle:

CSS styles

The overall behavior and appearance of the templates is created by a CSS style sheet: ui-dark.css. This is a Windows Library for JavaScript style sheet that defines the primary color scheme, fonts, and other style properties. The project reference is shown here:


<link href="//Microsoft.WinJS.1.0/css/ui-dark.css" rel="stylesheet">

You can change this reference in all of your HTML pages to ui-light.css, which is the recommended alternative color and style scheme for Windows Store apps:


<link href="//Microsoft.WinJS.1.0/css/ui-light.css" rel="stylesheet">

Most of the HTML pages in the Grid and Split project templates use one or more Windows Library for JavaScript templates (which are not the same as Visual Studio project and item templates) to format and display multiple instances of data. For example, wherever a ListView control is present on a page, you'll find a Windows Library for JavaScript template that has a class name of itemtemplate. The class names are used both to retrieve elements in the JavaScript files and to specify CSS. Here's the item template that's in items.html in the Split project template:


<div class="itemtemplate" data-win-control="WinJS.Binding.Template">
    <div class="item">
        <img class="item-image" src="#" data-win-bind="src: backgroundImage; alt: title" />
    <div class="item-overlay">
        <h4 class="item-title" 
            data-win-bind="textContent: title"></h4>
        <h6 class="item-subtitle win-type-ellipsis" 
            data-win-bind="textContent: subtitle"></h6>
    </div>
</div>


Important  The itemtemplate template is used for any type of ListView item, which might be a group or an individual data item, depending on context.

The CSS styles that are associated with the HTML pages, along with their Windows Library for JavaScript templates, are scoped CSS styles. The use of scoped styles limits the application of styles to particular pages. This can help to reduce the time it takes to fix problems that occur when the source of a particular CSS style isn't clear. An example of the use of scoped styles is shown here. This section of code, in items.css, shows CSS properties set for the preceding item template's IMG element. This element represents the associated image for each item in the ListView.


.itemspage .itemslist .item .item-image {
    -ms-grid-row-span: 2;
}


In the previous example, the itemspage entry sets the scope for the style, restricting the application of the CSS to elements that are in the itemspage DIV element declared in items.html. The itemslist entry further restricts the CSS to the main content section in the home page, and so on. The main content section in items.html, which declares the ListView, looks like this:


<div class="itemslist win-selectionstylefilled" 
    aria-label="List of groups" 
    data-win-control="WinJS.UI.ListView" 
    data-win-options="{ selectionMode: 'none' }">
</div>


Style sheet support for right-to-left writing systems is provided in the templates in Microsoft Visual Studio 2012 Update 1. The following example shows a CSS style for a group header displayed right-to-left in groupedItems.css (Grid template).


.groupeditemspage .groupeditemslist.win-rtl .group-header .group-chevron:before {
    content: "\E26C";
}

To use the right-to-left styles, you must include resources for a right-to-left language in your project, and Windows must be set to the correct language settings. For more info, see Quickstart: translating UI resources. For guidelines on supporting right-to-left writing systems in Windows Store apps, see How to support bi-directional UI.

Handling view state

Project templates like Grid and Split are designed to handle several view states, including portrait, snapped, full screen, and filled. For more info about the view states in Windows Store apps, see Guidelines for layouts. The Grid and Split templates handle view state within the project template navigation model. For more info, see navigation model.

In the same way that the navigation control (PageControlNavigator) passes a location (a page URI) and a state when it loads a page, it also passes information about the view state. First, in navigator.js, the navigation control creates a handler for the window.onresize event.


window.onresize = this._resized.bind(this);


In the constructor code for PageControlNavigator, the onresize event maps eventually to the updateLayout function that's implemented in the JavaScript file associated with the current HTML page. At run time, the onresize event calls this function, which forwards the view state to the page.

The implementation of updateLayout is specific to each page. This code shows the implementation of updateLayout and _initializeLayout in items.js in the Split template. (The items page is the home page that enables the user to select a group from a ListView. When the user selects the group, the app navigates to the split-view page, that is, the master/detail view.)


updateLayout: function (element, viewState, lastViewState) {
     /// <param name="element" domElement="true" />
     var listView = element.querySelector(".itemslist").winControl;
     if (lastViewState !== viewState) {
          if (lastViewState === appViewState.snapped || viewState === appViewState.snapped) {
               var handler = function (e) {
               listView.removeEventListener("contentanimating", handler, false);
               e.preventDefault();
          }
          listView.addEventListener("contentanimating", handler, false);
          var firstVisible = listView.indexOfFirstVisible;
          this._initializeLayout(listView, viewState);
          if (firstVisible >= 0 && listView.itemDataSource.list.length > 0) {
                listView.indexOfFirstVisible = firstVisible;
           }
       }
   }
},

_initializeLayout: function (listView, viewState) {

    if (viewState === appViewState.snapped) {
        listView.layout = new ui.ListLayout();
    } else {
        listView.layout = new ui.GridLayout();
    }
},


The first line of code in updateLayout gets the ListView control by using the querySelector method:


var listView = element.querySelector(".itemslist").winControl;

The remaining code in updateLayout checks view state, sets up an animation (not shown), and then calls _initializeLayout. _initializeLayout sets the horizontal or vertical arrangement of items in the ListView. If the current view is the snapped view, items are arranged vertically. Otherwise, items are arranged in a grid view.


if (viewState === appViewState.snapped) {
    listView.layout = new ui.ListLayout();
} else {
    listView.layout = new ui.GridLayout();
}


The pattern shown in these code examples is used by the Split and Grid templates. The Split template also supports unique behavior related to view state. By default, the split-view page (split.html) in the Split template is a two-column view—the master/detail view. The Split template also defines an alternative view called a single-column view when the view state is either snapped or portrait. The code that defines and handles this view state is in split.js. The _isSingleColumn function defines the single-column view state:


_isSingleColumn:  function () {
    var viewState = Windows.UI.ViewManagement.ApplicationView.value;
    return (viewState === appViewState.snapped || viewState === appViewState.fullScreenPortrait);
},


The _updateVisibility function is one of several functions in split.js that call _isSingleColumn. The _updateVisibility function turns the visibility of the columns on and off, depending on the current view state and the selected item. This function is called in split.js by the ready function when the page is loaded, and also by updateLayout when the view state changes. First, the function removes the primary column if one was previously defined (that is, if the app was already in single-column view).


_updateVisibility: function () {
    var oldPrimary = document.querySelector(".primarycolumn");
    if (oldPrimary) {
        utils.removeClass(oldPrimary, "primarycolumn");
    }
    if (this._isSingleColumn()) {
        if (this._itemSelectionIndex >= 0) {
            utils.addClass(document.querySelector(".articlesection"), "primarycolumn");
            document.querySelector(".articlesection").focus();
        } else {
            utils.addClass(document.querySelector(".itemlistsection"), "primarycolumn");
            document.querySelector(".itemlist").focus();
        }
    } else {
        document.querySelector(".itemlist").focus();
    }
}


If the app is in single-column view, _updateVisibility specifies a new primary column, adding the column type that corresponds to the selected item. If there's an item selected, updateVisibility adds the item details section (articlesection in the HTML), as shown here.


utils.addClass(document.querySelector(".articlesection"), "primarycolumn");

If no item is selected, updateVisibility adds the item list section instead (itemlistsection in the HTML), as shown here.


utils.addClass(document.querySelector(".itemlistsection"), "primarycolumn");

Several functions in split.js modify the Back button history or navigation behavior depending on the view state. The ready function and the updateLayout function modify the Back button history. The selectionChanged function, which is called when an item in the list view is selected, modifies the navigation behavior. We won't be looking at more examples here. For more info on managing view state, see Guidelines for layouts.

 

 

Build date: 3/11/2013

Did you find this helpful?
(1500 characters remaining)
© 2013 Microsoft. All rights reserved.