big bang theory of javascript metro applications
TRANSCRIPT
![Page 1: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/1.jpg)
Big Bang Theory of JavaScript Metro Applications
Евгений ЖарковSilverlight MVP, EPAM
![Page 2: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/2.jpg)
Агенда
• Обзор и основы платформы HTML5• Жизненный цикл приложений• Использование богатых возможностей JavaScript
и Windows Runtime• JavaScript шаблоны и WinJS помощники • Использование сторонних JavaScript библиотек• Безопасность контейнера приложения
![Page 3: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/3.jpg)
Создавать Windows 8 приложения с помощью HTML, CSS и JavaScript
легко и просто
![Page 4: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/4.jpg)
Windows 8 приложения с HTML5
Упаковка&
Runtime
Веб-платформ
а
Жизненный цикл
WINRT платформ
а
![Page 5: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/5.jpg)
Упаковка и Runtime
![Page 6: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/6.jpg)
От файлов до запуска
C:\Program Files\ Applications\...
HTML
CSS
JavaScript
Resources
Manifest App Container
HTML Host Process
App Code
App p
ack
age
Runnin
g a
pp
![Page 7: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/7.jpg)
Упаковка & Runtime
Быстрое создание простого приложения• Анатомия HTML5 приложения • Контейнер приложения и среда
исполнения
демо
![Page 8: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/8.jpg)
Windows 8 приложения с HTML5
Упаковка&
Runtime
Веб-платформ
а
Жизненный цикл
WINRT платформ
а
a
![Page 9: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/9.jpg)
Веб-платформа
![Page 10: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/10.jpg)
Платформа HTML-приложения
App Container
HTML Host Process
Internet Explorer
WebPlatform
TAB
App Code
Web Platform
WindowsRuntime
App Code
![Page 11: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/11.jpg)
HTML, CSS, JavaScript
• HTML5• Indexed DB• App Cache• Web Workers• Canvas• SVG• FormData
• CSS3 animations & transitions
• XHR• FileAPI• Web Sockets• Geolocation• PostMessage
![Page 12: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/12.jpg)
Простота платформы Windows для HTML5 приложений• Единственный HTML5 DOCTYPE
• Стандартизированый веб, без плагинов
• Одно окно
+ Доступ к Windows Runtime
![Page 13: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/13.jpg)
Windows Library для JavaScript (WinJS)библиотека для создания новых приложений, используя JavaScript• Делайте ваши приложения понятными и удобными• Соответствие новому дизайну Windows приложений• Контроль общего пользовательского опыта• Разрабатка для сенсорного и традиционного управления• Масштабирование под разные форм-факторы
• Создавайте ваши приложения быстро и качественно• Веб-технологии, с которыми вы уже знакомы• Современные шаблоны для отзывчивых приложений• Используйте интерактивные средства проектирования
![Page 14: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/14.jpg)
Windows 8 приложения с HTML5
Упаковка&
Runtime
Веб-платформ
а
Жизненный цикл
WINRT платформ
а
a a
![Page 15: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/15.jpg)
Жизненный цикл
![Page 16: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/16.jpg)
Переход состояний
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
![Page 17: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/17.jpg)
sessionState в Windows Library для JavaScript (WinJS) может помочь.
Используйте Windows.Storage.ApplicationData
для сохранения состояний
![Page 18: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/18.jpg)
Активация
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
![Page 19: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/19.jpg)
www.buildwindows.com
Windows 8 приложения с HTML5
Упаковка&
Runtime
Веб-платформ
а
Жизненный цикл
WINRT платформ
а
a a a
![Page 20: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/20.jpg)
Используйте возможности Windows
![Page 21: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/21.jpg)
![Page 22: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/22.jpg)
?
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
![Page 23: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/23.jpg)
Share contract
Source App Target AppData Packa
ge
![Page 24: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/24.jpg)
Windows 8 приложения с HTML5
Упаковка&
Runtime
Веб-платформ
а
Жизненный цикл
WINRT платформ
а
a a aa
![Page 25: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/25.jpg)
Шаблоны JavaScript
![Page 26: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/26.jpg)
Область видимости переменных
• 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
![Page 27: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/27.jpg)
Управление областями видимости
• DON’T: Use globals without a plan• DON’T: Forget the “var” keyword
• DO: use the module pattern• DO: use namespaces to manage globals
![Page 28: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/28.jpg)
The Module Pattern
(function () { var a = 10;
function somePrivateStuff() { a = 15; } WinJS.Navigation.navigate("/html/firstPage.html");})();
![Page 29: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/29.jpg)
Objects as Namespaces
(function () { function somethingUseful() { }
window.MyNamespace = window.MyNamespace || {}; window.MyNamespace.somethingUseful = somethingUseful;
})();
MyNamespace.somethingUseful();
![Page 30: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/30.jpg)
Helper For Namespaces
• In base.js• WinJS.Namespace.define• WinJS.Namespace.withParent
![Page 31: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/31.jpg)
Objects as Namespaces With WinJS
WinJS.Namespace.define("MyNamespace", { somethingUseful: function () { }});
MyNamespace.somethingUseful();
![Page 32: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/32.jpg)
Module + “Exports”
(function () {
function somethingPrivate() { }
function somethingUseful() { }
WinJS.Namespace.define("MyNamespace", { somethingUseful : somethingUseful });})();
![Page 33: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/33.jpg)
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
![Page 34: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/34.jpg)
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);
![Page 35: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/35.jpg)
Defining Objects
• DON’T: Define shared members in the object’s constructor
• DO: Define shared members on the object’s prototype
![Page 36: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/36.jpg)
Defining Objects
// DON’T do this function MyThing() { this.method1 = function() { } }
// DO this function MyThing() { } MyThing.prototype.method1 = function(){}
![Page 37: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/37.jpg)
Why?
• Memory savings• Pointer, function object used once instead of copied into
each instance• Perf improvements• Runtime optimizes name lookup based on prototypes
![Page 38: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/38.jpg)
Helper for Defining Prototypes
• WinJS.Class.define(ctor, { members }, { statics });• Attaches members to the prototype• Attaches statics to the constructor function
![Page 39: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/39.jpg)
Defining Objects with WinJS
var MyThing = WinJS.Class.define( function() { }, { method1: function() { } });
![Page 40: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/40.jpg)
Reusing Code
• DON’T: Create deep prototype chains
• DO: Consider using mixins
![Page 41: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/41.jpg)
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;
![Page 42: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/42.jpg)
Why?
• Performance• Prototype chains slow down property access
• Clarity• Where’s that property coming from?
![Page 43: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/43.jpg)
Helper for Mixins
• WinJS.Class.mix(ctor, mixin, mixin, …);
![Page 44: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/44.jpg)
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);
![Page 45: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/45.jpg)
Сторонние JavaScript библиотеки
![Page 46: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/46.jpg)
The JavaScript Ecosystem
• jQuery• ExtJS• YUI• MooTools• Prototype• Backbone• Underscore• Etc, etc, etc…
![Page 47: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/47.jpg)
It just works! Except…
• XHR differences• Host Enforcement• Local vs. Web Context
![Page 48: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/48.jpg)
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/
![Page 49: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/49.jpg)
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>
![Page 50: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/50.jpg)
Knockout .js
function initialize() { // Activates knockout.js ko.applyBindings(new ReservationsViewModel()); }
document.addEventListener("DOMContentLoaded", initialize, false);})();
![Page 51: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/51.jpg)
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 } ];}
![Page 52: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/52.jpg)
CoffeeScript
![Page 53: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/53.jpg)
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
![Page 54: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/54.jpg)
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!
![Page 55: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/55.jpg)
Host Enforcement
![Page 56: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/56.jpg)
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
![Page 57: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/57.jpg)
Local Context
• Full access to WinRT• Limited access to the web• Can’t navigate to arbitrary URLs• Can’t pull down external scripts
![Page 58: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/58.jpg)
Web Context
• Full access to the web• Can navigate to arbitrary URLs• Can pull scripts from arbitrary URLs• No access to the WinRT
![Page 59: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/59.jpg)
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
![Page 60: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/60.jpg)
Environment
![Page 61: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/61.jpg)
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
![Page 62: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/62.jpg)
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>
![Page 63: Big Bang Theory of JavaScript Metro Applications](https://reader035.vdocument.in/reader035/viewer/2022062319/5560b520d8b42af43b8b4908/html5/thumbnails/63.jpg)
Евгений Жарковt - @2j2ee - [email protected]