Wednesday, December 07, 2011

WinJS: Windows Library for Javascript (Windows 8)

[Tech - Software Blog]

If you haven't done the first JavaScript Metro app, see
Building your first Windows Metro style app with JavaScript.

Here is the official Microsoft intro:

and one with a light) that give your app the look and feel of Windows Developer Preview.


What is the Windows Library for JavaScript?

The Windows Library for JavaScript is a library of CSS and JavaScript files. It contains JavaScript objects, organized into namespaces, designed to make developing Metro style app using JavaScript easier. Windows Library for JavaScript includes objects that help you handle activation, access storage, and define your own classes and namespaces. It also includes a set of controls:

AppBarAn app toolbar that displays commands. reference
html: <div data-win-control="WinJS.UI.AppBar">
JavaScript:var object = new WinJS.UI.AppBar(element, options);
DatePickerEnables the user to select a date. reference

javscript:var datePicker = new Win.UI.DatePicker(element, options);
FlipViewDisplays a collection of items, one item at a time.
FlyoutDisplays a message that requires user interaction. (Unlike a dialog box, a Flyout does not create a separate window.)
ListViewDisplays a collection of items in a grid or list layout.
javascript var object = new WinJS.UI.ListView(parentObject, options);
RatingEnables the user to rate an item.
SemanticZoomProvides a way to manage and present two semantic views (abstractions) for a single set of structured, hierarchical data or content (such as the folder structure of a computer, a library of documents, or a photo album).
SettingsPaneProvides access to app settings.
TimePickerEnables the user to select a time.
javascipt var object = new WinJS.UI.TimePicker(parentObject);
ToggleRepresents an item that can be turned on or off.
TooltipDisplays a tooltip that can support rich content (such as images and formatted text) to show more info about an object.
ViewBoxScales a single child element to fill the available space without resizing it. The control reacts to changes in the size of the container, as well as changes in size of the child element. For example, this control responds if a media query results in a change in aspect ratio.

Windows Library for JavaScript also provides styling features in the form of CSS styles and classes that you can use or override. (Control styling is described in Quickstart: styling controls.)

Adding the Windows Library for JavaScript to your page

To use Windows Library for JavaScript, your app must contain the Windows Library for JavaScript files and each page that uses Windows Library for JavaScript features must have the proper CSS and script references.
When you use Microsoft Visual Studio 11 Express for Windows Developer Preview to create a Metro style app using JavaScript, it automatically includes the files you need.
However, depending on which template you use, your pages might or might not contain all the CSS and script references you need. To fix that, replace any existing Windows Library for JavaScript references with these references:
The previous markup contains two style sheets; remove the style sheet that you don't want to use (ui-light.css or ui-dark.css). Leaving them both in won't cause any problems, but whichever one is included last will override the one included before it.

Adding a WinJS control in markup

Unlike HTML controls, Windows Library for JavaScript controls don't have dedicated markup elements: you can't create a Rating control by adding a element, for example. To add a Windows Library for JavaScript control, you create a div element and use the data-win-control attribute to specify the type of control you want. To add a Rating control, you'd set the attribute to "WinJS.UI.Rating".
You must also call the WinJS.UI.processAll function in your JavaScript code. WinJS.UI.processAll parses your markup and instantiates any Windows Library for JavaScript controls it finds. It's best to call WinJS.UI.processAll in your DOMContentLoaded event handler or by using the WinJS.Utilities.ready function.
Hh465493.wedge(en-us,WIN.10).gifTo add a WinJS control
  1. Create a div element where you want to place the control. Set its data-win-control attribute to the fully qualified name of the control you want to create. This example creates a Rating control.
        Controls sample
        Create a WinJS control in markup
  2. In your JavaScript code, create a DOMContentLoaded event listener that calls the WinJS.UI.processAll function.
    (function () {
        'use strict';
        WinJS.Application.onmainwindowactivated = function (e) {
            if (e.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
                // TODO: Put your startup code here.
        document.addEventListener("DOMContentLoaded", function (e) {
    The WinJS.UI.processAll function processes the document and activates any Windows Library for JavaScript controls that you've declared in markup.
When you run the app, the Rating control appears where you positioned the div host element.
A rating control

Setting the properties of a WinJS control in markup

When you create an HTML control, you can set its properties using dedicated attributes. For example, to set the type, min, and max properties of an input control, you can set the type, min, and max attributes in your markup:
Unlike HTML controls, Windows Library for JavaScript controls don't have dedicated element or attribute tags; for example, you couldn't create a Rating control and set its properties using the this markup:

Instead, you use the data-win-options attribute to set a property in markup. It takes a string that contains one or more property value pairs:
data-win-options="{propertyName: propertyValue}"

This example sets the maxRating of a Rating control to 10.
When you run the app, the Rating control looks like this:
Rating control shows a 10 star rating system.
To set more than one property, separate them with a comma:
data-win-options="property1Name: property1Value, property2Name: property2Value"

The next example sets two properties of the Rating control.
When you run the app, the Rating control now looks like this:
Rating control shows a rating of 6 out of 10 stars.
If the property value is itself a string, enclose it in a different type of quote (' or ") than you used to set the data-win-options attribute. This example shows how to set the TimePicker control's current property, which takes a string:
To find out if a property is supported by a given Windows Library for JavaScript control, see its reference page.

Retrieving a control that you created in markup

You can also set the properties of a Windows Library for JavaScript control programmatically. To access the control in code, call the WinJS.UI.getControl function to retrieve the control from its host element. In the previous examples, the host element is "ratingControlHost".
var control = WinJS.UI.getControl(document.getElementById("ratingControlHost")); 

In some cases, you might want to retrieve and manipulate the control as soon as it's available. Be aware that the WinJS.UI.processAll method is asynchronous, so any code that follows it might run before WinJS.UI.processAll has completed. Given this, don't immediately try to manipulate the control because it might not be available :

// Don't do this:
var control = WinJS.UI.getControl(document.getElementById("ratingControlHost")); 
control.averageRating = 6; 

The WinJS.UI.processAll returns a WinJS.Promise object that you can use to call a function when the WinJS.UI.processAll method completes. Here the example defines a completion function that retrieves the control and sets its averageRating to 3.
// Do this instead:
    .then(function () {

        var control = WinJS.UI.getControl(document.getElementById("ratingControlHost"));
        control.averageRating = 3; 

The next section describes how to use the WinJS.UI.getControl function to retrieve a control and add event listeners.

Handling events for WinJS controls

Just like with HTML controls, the preferred way to attach event listeners for a Windows Library for JavaScript control is to use the addEventListener function. Retrieving a Windows Library for JavaScript control is a bit different than retrieving an HTML control, however.
To handle an event:
  1. In your JavaScript, use the WinJS.UI.getControl to retrieve the control from its host element.
  2. Call the control's addEventListener function and specify an event and an event handler.
The next example shows how to handle the change event of a Rating control.
Hh465493.wedge(en-us,WIN.10).gifTo handle the change event of a rating control
  1. In your HTML file, add a paragraph and give it an ID of "outputParagraph". Your event listener will output to this paragraph.
        Create a WinJS control in markup
  2. In your JavaScript, create an event listener function called ratingChanged that takes one parameter. This next example creates an event listener that displays the properties and values contained by the event information object.
        function ratingChanged(eventInfo)
            var outputParagraph = document.getElementById("outputParagraph"); 
            var output = eventInfo.type + ": 
      "; for(property in eventInfo) { output += "
    • " + property + ": " + eventInfo[property] + "
    • "; } outputParagraph.innerHTML = output + "
    "; }
  3. Use the WinJS.UI.getControl method to retrieve the control from its host element and call the addEventListener function to add your event handler. This example retrieves the control as soon as it's created and adds the event handler:
        document.addEventListener("DOMContentLoaded", function (e) {
                .then(function () {
               var control = WinJS.UI.getControl(document.getElementById("ratingControlHost"));
               control.addEventListener("change", ratingChanged, false);
When you run the app and change the rating, it creates a list of event information properties and values.
The output from the change event.

Adding a WinJS control in code

The previous examples showed you how to create and manipulate a Windows Library for JavaScript control that you created in your markup, but you can also create a Windows Library for JavaScript control using JavaScript code instead.
Hh465493.wedge(en-us,WIN.10).gifTo create a WinJS control in code
  1. In your markup, create the element that will host your control.
  2. In your code (preferably in your DOMContentLoaded event handler), retrieve the host element.
    var hostElement = document.getElementById("hostElement");
  3. Create your control by calling its constructor and passing the host element to the constructor. This example creates a Rating control:
    var ratingControl = new WinJS.UI.Rating(hostElement); 
    When you run the program, it displays the Rating you created:
    A rating control created in code
    There's no need to call WinJS.UI.processAll—you only need to call WinJS.UI.processAll when you create a Windows Library for JavaScript control in markup.

Summary and next steps

You learned how to create Windows Library for JavaScript controls, how to set their properties, and how to attach event handlers.
The next topic, Quickstart: styling controls, describes how to use Cascading Style Sheets (CSS) and the enhanced styling capabilities of Metro style apps using JavaScript. To learn more about specific controls, see the Controls list and Controls by function topics.


No comments: