390 likes | 573 Views
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.
E N D
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 • 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.
Pro tip: • Consider having multiple event handlers for different conditions: • app.addEventListener(“activated”, function launchActivation() { • app.addEventListener(“activated”, function searchActivation() { • app.addEventListener(“activated”, function protocolActivation() {
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 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.Navigationnamespace offers functionality for back(), forward(), navigate(). • WinJS.UI.Pages are a good navigation target.
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.
Windows 8 apps are a highly asynchronous environment. • 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.
Promises: chaining operations • // Issue an XHR, process the result, and then do it again, and again • myXhr(url1).then(function (result) { • console.log("done processing first url: " + url1); • returnmyXhr(url2); • }).then(function (result) { • console.log("done processing second url: " + url2); • returnmyXhr(url3); • });
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 • // Using array's reduce operator: • urls.reduce(function (prev, url, i) { • return Promise.as(prev).then(function () { • returnmyXhr(url); • }).then(function (result) { • console.log(i + ", done processing url: " + url); • }); • });
Promises: joining for concurrency • // all xhr's are issued immediately and everything is processed • // when all the requests have returned • Promise.join( • urls.map(function (url) { return myXhr(url); }) • ).then(function (results) { • results.forEach(function (result, i) { • console.log("url: " + urls[i] + ", " + result); • }); • });
Promises: parallel with sequential results • // all xhr's are issued immediately and are processed as they • // return as long as all previous xhr's have been processed • var processed = urls.reduce(function (prev, url, i) { • var result = myXhr(url); • returnPromise.join({ prev: prev, result: result}).then(function (v) { • console.log(i + ",url: " + url + ", " + v.result); • }); • });
Promises: errors • There are two continuation methods on promise. • then(): yields a promise, which can be chained • done(): yields nothing • Use .done() everywhere you can and place a breakpoint in WinJS to catch unhandled errors. • Asynchronous errors are hard to find; logging is your friend.
Data binding • <div id="bound" data-win-bind="style.backgroundColor: color; textContent: text"></div> • <script> • vardata = WinJS.Binding.as({ color: "red", text: "Some text!" }); • WinJS.Binding.processAll(document.getElementById("bound"), data): • varcolors = ["red", "green", "blue", "pink", "white"] • varcurrent = 0; • setInterval(function () { data.color= colors[++current % colors.length]; }, 1000); • </script>
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.Templatecontrol allows writing down data bindings in a manner that is easily instantiated in collection contexts. • WinJS.Binding.Listapproximates 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 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 FlipViewcontrol by using its .dataSourceproperty. • 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.
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.
Related Sessions • 11/1 @ 2:30 – B33 KodiakDeep dive on WinJS ListView • 11/1 @ 4:15 – B92 Nexus/NormandyModern JavaScript
Resources • 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 Please submit session evals by using the Build Windows 8 app or at http://aka.ms/BuildSessions