building great winjs apps

39
Building great WinJS apps Josh Williams / Chris Anderson Engineer / Distinguished Engineer 4-101 – Deep Dive into WinJS

Upload: brooke

Post on 24-Feb-2016

74 views

Category:

Documents


0 download

DESCRIPTION

Building great WinJS apps. Josh Williams / Chris Anderson Engineer / Distinguished Engineer 4-101 – Deep Dive into WinJS. Building great WinJS apps. Structuring an application Navigation Promises Data binding. Structuring an application. Structuring an application. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Building great WinJS apps

Building great WinJS apps

Josh Williams / Chris AndersonEngineer / Distinguished Engineer4-101 – Deep Dive into WinJS

Page 2: Building great WinJS apps

Structuring an applicationNavigationPromisesData binding

Building great WinJS apps

Page 3: Building great WinJS apps

Structuring an application

Page 4: Building great WinJS apps

Structuring an application

The WinJS.Application object hosts lifecycle events: activation, checkpoint, settings, error.Hang application state off of the app object:var app = WinJS.Application;app.myState = 1;app.addEventListener(“myevent”, …);app.dispatchEvent({ type: “myevent”, … });Add your own events, use app as a single event queue for sequentially processed events.

Make the app object your friend

Page 5: Building great WinJS apps

Structure: activation

WinJS.Application.onactivated: there are lots of different reasons you get activated.The default splash screen can only be up for a limited period of time and is inactive.If you want to defer splash screen dismissal for a short period of time, use the .setPromise() method on the event handler argument.For longer startup, use the extended splash screen pattern: http://aka.ms/splashscreen

Think about activation; it’s subtle.

Page 6: Building great WinJS apps

Consider having multiple event handlers for different conditions:app.addEventListener(“activated”, function launchActivation() {

app.addEventListener(“activated”, function searchActivation() {

app.addEventListener(“activated”, function protocolActivation() {

Pro tip:

Page 7: Building great WinJS apps

Let’s write a protocol handler

Page 8: Building great WinJS apps

Structure: checkpoint

WinJS.Application.oncheckpoint represents a key aspect of your app.Resume from suspend is different than resume from termination.WinJS.Application.sessionState is saved and restored automatically as long as you store data that can be serialized using JSON.Pro tip: If you build an app that deals with suspend and resume well, you’ll have an app that also deals with navigation well.

Your app is terminated by Process Lifetime Management (PLM). From the start, think about what the user’s experience is when this happens.

Page 9: Building great WinJS apps

Structure: errors

Exceptions happen. In the web, they are ignored and the page rambles on, sometimes with less functionality.In Windows 8, HTML/JS applications unhandled exceptions terminate the application.WinJS.Application.onerror is the place this bubbles up in WinJS.

The Windows 8 app host is less forgiving than the browser.

Page 10: Building great WinJS apps

Navigation in WinJS apps

Page 11: Building great WinJS apps

Navigation basics

Normal browser navigation isn’t supported in Windows 8 HTML/JS apps.WinJS provides a history stack; the expectation is that developers will build an app with an appropriate navigation scheme on top of it.The WinJS.Navigation namespace offers functionality for back(), forward(), navigate().WinJS.UI.Pages are a good navigation target.

Page 12: Building great WinJS apps

Building the simplest navigation we can

Page 13: Building great WinJS apps

Navigation in the Visual Studio templates

Using the templates in VS, you get navigator.js which handles some things for you:Animated transitions between pages.Hooking events for things like Alt-Left and the back button on your mouse so that navigation feels familiar.Don’t be afraid to customize the PageControlNavigator; different apps have different needs.

Page 14: Building great WinJS apps

Promises

Page 15: Building great WinJS apps

Promises are a mechanism for abstracting and composing asynchrony.Based on the CommonJS Promises/A spec (http://wiki.commonjs.org/wiki/Promises/A).Very easy to use initially and can quickly get complicated.

Windows 8 apps are a highly asynchronous environment.

Page 16: Building great WinJS apps

Simply wrapping XHR in a promise

Page 17: Building great WinJS apps

// Issue an XHR, process the result, and then do it again, and againmyXhr(url1).then(function (result) { console.log("done processing first url: " + url1); return myXhr(url2);}).then(function (result) { console.log("done processing second url: " + url2); return myXhr(url3);});

Promises: chaining operations

Page 18: Building great WinJS apps

Promises: Chaining operations

The success handler of the chained promise gets the result of executing the prior success handler in the chain.Remember the return.Allows orchestrating complex asynchronous processes.Errors for an entire chain can be handled in one place.p.then(s1).then(s2).then(null, errorHandler)

The result of calling .then() on a promise is a new promise.

Page 19: Building great WinJS apps

Promises: chaining a list of operations

Task 1

Task 2

Task 3

Task 4

0 2 4 6 8 10 12

Page 20: Building great WinJS apps

// Using array's reduce operator:urls.reduce(function (prev, url, i) { return Promise.as(prev).then(function () { return myXhr(url); }).then(function (result) { console.log(i + ", done processing url: " + url); });});

Promises: chaining a list of operations

Page 21: Building great WinJS apps

Promises: joining for concurrency

Task 1

Task 2

Task 3

Task 4

0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5

Page 22: Building great WinJS apps

// all xhr's are issued immediately and everything is processed// when all the requests have returnedPromise.join( urls.map(function (url) { return myXhr(url); })).then(function (results) { results.forEach(function (result, i) { console.log("url: " + urls[i] + ", " + result); });});

Promises: joining for concurrency

Page 23: Building great WinJS apps

Promises: parallel with sequential results

Task 1

Task 2

Task 3

Task 4

0 1 2 3 4 5 6

Page 24: Building great WinJS apps

// all xhr's are issued immediately and are processed as they// return as long as all previous xhr's have been processedvar processed = urls.reduce(function (prev, url, i) { var result = myXhr(url); return Promise.join({ prev: prev, result: result}).then(function (v) { console.log(i + ",url: " + url + ", " + v.result); });});

Promises: parallel with sequential results

Page 25: Building great WinJS apps

There are two continuation methods on promise.then(): yields a promise, which can be chaineddone(): yields nothingUse .done() everywhere you can and place a breakpoint in WinJS to catch unhandled errors.Asynchronous errors are hard to find; logging is your friend.

Promises: errors

Page 26: Building great WinJS apps

Visual Studio Exceptions dialog

Page 27: Building great WinJS apps

Data binding

Page 28: Building great WinJS apps

<div id="bound" data-win-bind="style.backgroundColor: color; textContent: text"></div>

<script> var data = WinJS.Binding.as({ color: "red", text: "Some text!" }); WinJS.Binding.processAll(document.getElementById("bound"), data):

var colors = ["red", "green", "blue", "pink", "white"] var current = 0; setInterval(function () { data.color = colors[++current % colors.length]; }, 1000);</script>

Data binding

Page 29: Building great WinJS apps

Data binding in WinJS

Observables: WinJS.Binding.as()The data-win-bind attribute offers a declarative way to specify live JavaScript property assignments.WinJS.Binding.Template control allows writing down data bindings in a manner that is easily instantiated in collection contexts.WinJS.Binding.List approximates a data-bound JavaScript array.

WinJS binding system is factored into four parts.

Page 30: Building great WinJS apps

Data binding: initializers

Data binding attribute syntax is: ‘<dest>: <source> <initializer?>’.WinJS ships with a number of initializers:WinJS.Binding.defaultBind: default.WinJS.Binding.onetime: no reoccurring binding.WinJS.Binding.setAttribute: sets an attribute on the target DOM element instead of a JavaScript property.WinJS.Binding.setAttributeOneTime: setAttribute + onetime.

WinJS data binding initializers are the way to break out of the box and extend our binding system.

Page 31: Building great WinJS apps

Writing a binding converter

Page 32: Building great WinJS apps

Writing two-way binding initializer supporting the ‘onchange’ event

Page 33: Building great WinJS apps

Data binding lists

WinJS.Binding.List has the API of JavaScript’s array with some additions.Except for .setAt/.getAt ,which stand in for [i].Works with a ListView or FlipView control by using its .dataSource property.Offers live updates to the collection UI.Offers a set of events that you can build your own data bound UI on top of.

Binding.List looks and feels like an array.

Page 34: Building great WinJS apps

Creating a ListView bound to a WinJS.Binding.List

Page 35: Building great WinJS apps

Data binding lists: projections

WinJS.Binding.List offers a number of live projections over its collection.createFiltered(predicate)createSorted(sorter)createGrouped(groupKey, groupData)Each of these provide a view over the list, which is kept up to date as the underlying data changes.These projections can be stacked.

Binding.List’s projections are live views over the underlying collection.

Page 36: Building great WinJS apps

Grouping our list of data

Page 37: Building great WinJS apps

• 11/1 @ 2:30 – B33 KodiakDeep dive on WinJS ListView

• 11/1 @ 4:15 – B92 Nexus/NormandyModern JavaScript

Related Sessions

Page 39: Building great WinJS apps

© 2012 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.