building great winjs apps
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 PresentationTRANSCRIPT
Building great WinJS apps
Josh Williams / Chris AndersonEngineer / Distinguished Engineer4-101 – Deep Dive into WinJS
Structuring an applicationNavigationPromisesData binding
Building great WinJS apps
Structuring an application
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
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.
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:
Let’s write a protocol handler
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.
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.
Navigation in 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.
Building the simplest navigation we can
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.
Promises
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.
Simply wrapping XHR in a promise
// 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
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.
Promises: chaining a list of operations
Task 1
Task 2
Task 3
Task 4
0 2 4 6 8 10 12
// 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
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
// 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
Promises: parallel with sequential results
Task 1
Task 2
Task 3
Task 4
0 1 2 3 4 5 6
// 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
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
Visual Studio Exceptions dialog
Data binding
<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
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.
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.
Writing a binding converter
Writing two-way binding initializer supporting the ‘onchange’ event
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.
Creating a ListView bound to a WinJS.Binding.List
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.
Grouping our list of data
• 11/1 @ 2:30 – B33 KodiakDeep dive on WinJS ListView
• 11/1 @ 4:15 – B92 Nexus/NormandyModern JavaScript
Related Sessions
• Develop: http://msdn.microsoft.com/en-US/windows/apps/br229512
• Design: http://design.windows.com/
• Samples: http://code.msdn.microsoft.com/windowsapps/Windows-8-Modern-Style-App-Samples
• Videos: http://channel9.msdn.com/Windows
Resources
Please submit session evals by using the Build Windows 8 appor at http://aka.ms/BuildSessions
© 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.