Big Bang Theory of JavaScript Metro Applications

Post on 24-May-2015

307 views 0 download

Tags:

transcript

Big Bang Theory of JavaScript Metro Applications

Евгений ЖарковSilverlight MVP, EPAM

Агенда

• Обзор и основы платформы HTML5• Жизненный цикл приложений• Использование богатых возможностей JavaScript

и Windows Runtime• JavaScript шаблоны и WinJS помощники • Использование сторонних JavaScript библиотек• Безопасность контейнера приложения

Создавать Windows 8 приложения с помощью HTML, CSS и JavaScript

легко и просто

Windows 8 приложения с HTML5

Упаковка&

Runtime

Веб-платформ

а

Жизненный цикл

WINRT платформ

а

Упаковка и Runtime

От файлов до запуска

C:\Program Files\ Applications\...

HTML

CSS

JavaScript

Resources

Manifest App Container

HTML Host Process

App Code

App p

ack

age

Runnin

g a

pp

Упаковка & Runtime

Быстрое создание простого приложения• Анатомия HTML5 приложения • Контейнер приложения и среда

исполнения

демо

Windows 8 приложения с HTML5

Упаковка&

Runtime

Веб-платформ

а

Жизненный цикл

WINRT платформ

а

a

Веб-платформа

Платформа HTML-приложения

App Container

HTML Host Process

Internet Explorer

WebPlatform

TAB

App Code

Web Platform

WindowsRuntime

App Code

HTML, CSS, JavaScript

• HTML5• Indexed DB• App Cache• Web Workers• Canvas• SVG• FormData

• CSS3 animations & transitions

• XHR• FileAPI• Web Sockets• Geolocation• PostMessage

Простота платформы Windows для HTML5 приложений• Единственный HTML5 DOCTYPE

• Стандартизированый веб, без плагинов

• Одно окно

+ Доступ к Windows Runtime

Windows Library для JavaScript (WinJS)библиотека для создания новых приложений, используя JavaScript• Делайте ваши приложения понятными и удобными• Соответствие новому дизайну Windows приложений• Контроль общего пользовательского опыта• Разрабатка для сенсорного и традиционного управления• Масштабирование под разные форм-факторы

• Создавайте ваши приложения быстро и качественно• Веб-технологии, с которыми вы уже знакомы• Современные шаблоны для отзывчивых приложений• Используйте интерактивные средства проектирования

Windows 8 приложения с HTML5

Упаковка&

Runtime

Веб-платформ

а

Жизненный цикл

WINRT платформ

а

a a

Жизненный цикл

Переход состояний

RunningSuspend

ed

suspendingTerminat

edLow memory

Core runsNo code

runsNo

process

resuming

App has 5s to work after suspend

message

App is not notified when terminated

App is notified when resumed

Applaunch

Splash screen

Code runs

sessionState в Windows Library для JavaScript (WinJS) может помочь.

Используйте Windows.Storage.ApplicationData

для сохранения состояний

Активация

DOMContentLoaded

Load App Data, Setup Event Handlers, Initialize UI

Activated

Load Saved State, Handle

Activation Parameters

.onLoad

Finish Long Running Setup Activities

Splash Screen Displayed

www.buildwindows.com

Windows 8 приложения с HTML5

Упаковка&

Runtime

Веб-платформ

а

Жизненный цикл

WINRT платформ

а

a a a

Используйте возможности Windows

?

Blobs, streams & Windows runtime

function importFile() { var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.fileTypeFilter.replaceAll([".jpg", ".bmp", ".gif", ".png"]); picker.pickSingleFileAsync().then(function (file) {

//storage file from WinRT, stream of bytes var blobUrl = URL.createObjectURL(file);

img.src = blobUrl;}

XHR

File Picker

BLOB

Image Tag

Video Tag

Audio Tag

Share contract

Source App Target AppData Packa

ge

Windows 8 приложения с HTML5

Упаковка&

Runtime

Веб-платформ

а

Жизненный цикл

WINRT платформ

а

a a aa

Шаблоны JavaScript

Область видимости переменных

• JavaScript имеет:• Global scope• Function scope• Defaults to global

• Приложения используют единый контекст скриптов• Doesn’t do page navigation – scopes don’t reset• Each “page” will need different scripts• Global scope can get really busy• Note: CSS collides too

Управление областями видимости

• DON’T: Use globals without a plan• DON’T: Forget the “var” keyword

• DO: use the module pattern• DO: use namespaces to manage globals

The Module Pattern

(function () { var a = 10;

function somePrivateStuff() { a = 15; } WinJS.Navigation.navigate("/html/firstPage.html");})();

Objects as Namespaces

(function () { function somethingUseful() { }

window.MyNamespace = window.MyNamespace || {}; window.MyNamespace.somethingUseful = somethingUseful;

})();

MyNamespace.somethingUseful();

Helper For Namespaces

• In base.js• WinJS.Namespace.define• WinJS.Namespace.withParent

Objects as Namespaces With WinJS

WinJS.Namespace.define("MyNamespace", { somethingUseful: function () { }});

MyNamespace.somethingUseful();

Module + “Exports”

(function () {

function somethingPrivate() { }

function somethingUseful() { }

WinJS.Namespace.define("MyNamespace", { somethingUseful : somethingUseful });})();

Modules & Performance

• Use your module function’s parameters• Pass commonly used globals as parameters• Why• Clarity gain – you can see which globals you think you’re

using• Small perf gain – saves a lookup step

Using Module Parameters

a = 5;

(function (global, WinJS) { var q = WinJS.Utilities.query;

WinJS.UI.processAll().then(function () { q(".output").forEach(function (e) { e.innerText = a; }); });

})(window, WinJS);

Defining Objects

• DON’T: Define shared members in the object’s constructor

• DO: Define shared members on the object’s prototype

Defining Objects

// DON’T do this function MyThing() { this.method1 = function() { } }

// DO this function MyThing() { } MyThing.prototype.method1 = function(){}

Why?

• Memory savings• Pointer, function object used once instead of copied into

each instance• Perf improvements• Runtime optimizes name lookup based on prototypes

Helper for Defining Prototypes

• WinJS.Class.define(ctor, { members }, { statics });• Attaches members to the prototype• Attaches statics to the constructor function

Defining Objects with WinJS

var MyThing = WinJS.Class.define( function() { }, { method1: function() { } });

Reusing Code

• DON’T: Create deep prototype chains

• DO: Consider using mixins

Reusing Code

// DON’T do this function Ctor() { } Ctor.prototype.prototype = mixin;

// DO this function Ctor() { } Ctor.prototype.method1 = mixin.method1; Ctor.prototype.method2 = mixin.method2;

Why?

• Performance• Prototype chains slow down property access

• Clarity• Where’s that property coming from?

Helper for Mixins

• WinJS.Class.mix(ctor, mixin, mixin, …);

Example: Event mixinvar MyControl = WinJS.Class.mix( function (element, options) { this._domElement = element;

// your code here }, WinJS.UI.DOMEventMixin, WinJS.Utilities.createEventProperties({swizzle: 0, spin: 0}));

var c = new MyControl(element);c.onswizzle = function() { }c.addEventListener("spin", function () { }, false);

Сторонние JavaScript библиотеки

The JavaScript Ecosystem

• jQuery• ExtJS• YUI• MooTools• Prototype• Backbone• Underscore• Etc, etc, etc…

It just works! Except…

• XHR differences• Host Enforcement• Local vs. Web Context

jQuery, XHR, and the local context

• jQuery xhr now does a cross-domain check (new in 1.6)

• In local context, your origin is “ms-wwa://{something}”

• Cross domain check fails

• Workarounds• Use WinJS XHR• Tell jQuery to bypass the check• $.support.cors = true;• http://api.jquery.com/jQuery.support/

Knockout .js

<tbody data-bind="foreach: seats"> <tr> <td data-bind="text: name"></td> <td data-bind="text: meal().mealName"></td> <td data-bind="text: meal().price"></td> </tr> </tbody>

Knockout .js

function initialize() { // Activates knockout.js ko.applyBindings(new ReservationsViewModel()); }

document.addEventListener("DOMContentLoaded", initialize, false);})();

Knockout .js function SeatReservation(name, initialMeal) { var self = this; self.name = name; self.meal = ko.observable(initialMeal); } function ReservationsViewModel() { var self = this; self.availableMeals = [ { mealName: "Standard (sandwich)", price: 0 }, { mealName: "Premium (lobster)", price: 34.95 }, { mealName: "Ultimate (whole zebra)", price: 290 } ];}

CoffeeScript

Host Enforcement

• Prevents “bad” HTML from getting inserted• Script blocks, iframes, event handlers, etc.

• Kicks in when setting strings• innerHTML• outerHTML• setAdjacentHTML

• “data-” attributes in general not on the allowed list• WinJS specific ones are ok

Host Enforcement Escape Hatches

• Can work around when needed:• toStaticHTML method• Use DOM creation APIs• Use WinJS.Utilities.setInnerHTMLUnsafe (and company)• Use msWWA.execUnsafeLocalFunction

• DO A SECURITY REVIEW IF YOU BYPASS HOST ENFORCEMENT!

Host Enforcement

Local vs. Web Context

• We want access to the full features of Windows 8• WinRT• Sensors• File system• Etc.

• We want to pull data and logic from the web• Mashup apps (Bing maps)• External analytics• Advertising

• Web content may be evil

Local Context

• Full access to WinRT• Limited access to the web• Can’t navigate to arbitrary URLs• Can’t pull down external scripts

Web Context

• Full access to the web• Can navigate to arbitrary URLs• Can pull scripts from arbitrary URLs• No access to the WinRT

Controlling Your Context

• Depends on your URL scheme• http or https: Web Context• ms-wwa: Local Context• ms-wwa-web: Web Context

• Typically done using iframes• Can navigate your top level page too

Environment

Wrap up

• Use common JavaScript patterns to organize your code• Promotes maintainability• Improves performance

• Use the JavaScript libraries you already know and love• They mostly just work• Watch out for host enforcement, cross-domain checks,

local vs. web compartment differences

For More information

• Books on JavaScript Patterns• JavaScript: The Good Parts (O’Reilly)• JavaScript Patterns (O’Reilly)

• <Your Favorite JavaScript Library’s docs linked here>

Евгений Жарковt - @2j2ee - eu.zharkov@gmail.com