Windows 8 App Dev
With HTML and JavaScript
DEV322
Me
Aaron PowellReadify Senior Developer & Technical Specialist (Web)IE MVP@slacehttp://www.aaron-powell.comAuthor of Pinboard for Windows 8
This session
Windows 8 development with HTML & JavaScriptHow to approachGotchasLimitations
Approaching development
You are not building a website!
Not a website?
It’s a desktop applicationHTML is the markup languageJavaScript is the ‘code behind’
Many web rules don’t applyTrying to apply them will add complexity
You don’t have network latencyYou don’t have traditional page events
One engine to rule them all
You only have Trident & ChakraDon’t add unnecessary vender prefixes
-ms- when requiredMost features are prefix-free
You don’t need jQuery
Why no jQuery?
jQuery normalizes browser quirksBut you don’t have multiple browsers
Sizzle adds CSS selector queriesThis is native in IE10 (and IE9)WinJS has APIs for this
Most animations can be done with CSS3
Patterns
Like .NET JS patterns are importantWinJS is designed around some of the modern JS patterns
Namespacing
WinJS.Namespace.defineScope your code to a single location
Minimise global variablesStructure your API
Modules
Self-executing anonymous functionPass in what you require inside the functionModule responsible for an isolated piece of functionality
SRP ;)
Modules
(function (Tasks /*, dependencies */) {//do stuff
})(Tasks /*, some dependency */);
Dependency loaders
Require.js & Curl.js are popularThink DI but for JavaScript
//tasks.data.jsdefine([‘jquery’], function ($) {
return { ... };});//tasks.app.jsrequire([‘tasks.data’], function (data) {
//do stuff with our data API});
Dependency loaders and WinJS APIs
Don’t try and script load WinJS APIsWrap them into the loader
define(‘winjs’, function () {return WinJS;
});define(‘class’, [‘winjs’], function (winjs) {
return winjs.Class;});
Classes
JavaScript is prototypalNo class support at the language level
WinJS provides API-based supportWhy classes?
Useful for modelsUseful for unique instance objects
Classes
define([‘class’], function(klass) { 'use strict'; var task = klass.define(function() { this.created = new Date(); }, { name: '', description: '', done: false }); return { Task: task };});
Async all the things!
C# dev’s are raving about the async keywordEverything in JS is async
AJAX requestsAnimationsEvent handlersTimers
Simplifying async programming
Fire off *something* asynchronouslyWait for it to complete
React when it succeeds/ failsShouldn’t care about how to wire that up
AJAX
WinJS.xhrNo need for jQuery!
Little rawer than you might be use toManually control headersSubmitting form data requires manual setupResponse is raw
WinJS.Promise
API for exposing async operationsEg: AJAX
WinJS.xhr({url: ‘http://my-app/my-api’,method: ‘get’
}).then(success, failure);
Storage
Local storageRoaming storageSecurity storageOffline storage
Local or Roaming
Application setting storageEssentially a key/ value store
Local stores on the deviceUninstall and it’s gonePersists across upgrades though
Roaming stores in the cloudAgainst your Live IDUseful to sync multiple devices
var applicationData = Windows.Storage.ApplicationData.current;var localSettings = applicationData.localSettings;var roamingSettings = applicationData.roamingSettings;
localSettings.values.someProperty = ‘hello teched’;
if(roamingSettings.values.someOtherProperty) {//do stuff
}
Security storage
Need to store user credentials?Other secure data?PasswordVault
Access to Windows Web Credentials StoreStore two values
UsernamePassword
var key = ‘My Application’;var passwordVault = new Windows.Security.Credentials.PasswordVault();var user = passwordVault.findAllByResource(key)[0];
var creds = new Windows.Security.Credentials.PasswordCredential(key, username, password);passwordVault.add(creds);
Offline storage
Settings have finite limitsWhat if you need to store lots of data?No SQL serverIndexedDB!
IndexedDB
Part of HTML5Asynchronous storage APISQL-like
KeysIndexes‘Tables’TransactionsCloser to NoSQL
Background processing
Look into Web WorkersGame engine processingNumber crunchingAJAX requests to load unimportant data
var worker = new Worker(‘ms-appx:///js/worker.js’);worker.addEventListener(‘message’, function (evt) {
//handle worker doing stuff});
Tombstoning
Handle it with background processingListen for oncheckpoint
Tell WebWorkers to shut downUse setPromise to make it wait for youDon’t take too long, Windows will kill it anyway
Handle the resume to wake up your processes
Tombstoning
app.oncheckpoint = function (evt) {evt.detail.setPromise(new WinJS.Promise(function (done) {
worker.addEventListener(‘message’, function suspend(e) {if (e.data.shutdown) {
done();}
});
worker.postMessage({ shutdown: true });});
};
Gotcha’s
Don’t look at the DOM
The DOM
Although it’s HTML it’s not as we know it on the webYou’ll find a lot of auto-generated HTML
And it often doesn’t make sense
Controls
Existing JavaScript plugins eitherProduce problematic HTMLBreak Windows 8 UX guides
Stick with shipped controlsGridsListsSemantic Zoom
Or build your own
Watch your CSS
WinJS provides basic “skins”These style OOTB controls
The styles are pretty ridgedDesigned to keep you from making a messHard to work around
Probably shouldn’t do it!
Chakra is FAST
My app failed certification to an unusual bugIn release mode code was executing differently to debugAsync operations were “out of order”
Make sure you wait on async resultsUse Promise where possible
It’s COM wrapped in JavaScript
Many Win8 APIs are COMErgo many WinJS APIs are COMException Driven Development
PasswordVault throws an exception when there are no credentials
APIs are often not JavaScript friendlyTake a look at Tiles!
Limitation
Windows 8 sandbox
You’re limited in device accessNot as big a problem as in .NET
Common tasks may seem overly complex
It’s still technically a browser
You have some browser limitationsWatch out for CORSWatch out for DOM manipulation errors
It’s technically not a browser
Many additional eventsActivatedLoadedUnloadCheckpointResume
It’s statefulNew global objects
Binding
In-the-box binding is one-wayKnockout.js works
Limitations when combining with data source controls
Tooling
VS2012 is a real improvementJavaScript still has some issues
Debugging console sucksStack traces generally work
Except when Promises (async stuff) gets involvedSimulator is no substitute for actual devices
Final thoughts
My opinion
It’s a v1 productMany good thoughtsRadically different mindset to ‘web development’Better than XAML!
© 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.