1 / 39

Building great WinJS apps

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.

brooke
Télécharger la présentation

Building great WinJS apps

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. Building great WinJS apps • Structuring an application • Navigation • Promises • Data binding

  3. Structuring an application

  4. 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

  5. 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.

  6. 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() {

  7. Let’s write a protocol handler

  8. 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.

  9. 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.

  10. Navigation in WinJS apps

  11. 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.

  12. Building the simplest navigation we can

  13. 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.

  14. Promises

  15. 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.

  16. Simply wrapping XHR in a promise

  17. 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); • });

  18. 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.

  19. Promises: chaining a list of operations

  20. 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); • }); • });

  21. Promises: joining for concurrency

  22. 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); • }); • });

  23. Promises: parallel with sequential results

  24. 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); • }); • });

  25. 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.

  26. Visual Studio Exceptions dialog

  27. Data binding

  28. 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>

  29. 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.

  30. 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.

  31. Writing a binding converter

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

  33. 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.

  34. Creating a ListView bound to a WinJS.Binding.List

  35. 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.

  36. Grouping our list of data

  37. Related Sessions • 11/1 @ 2:30 – B33 KodiakDeep dive on WinJS ListView • 11/1 @ 4:15 – B92 Nexus/NormandyModern JavaScript

  38. 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

More Related