Zone.js
Brian Ford ← @briantford
What is Zone.js?
What is Zone.js?
"It's open-heart surgery on the web browser"
–Miško
What is a Zone?
It's an execution context.
Cool.
execution context
Async JavaScript
// code
a();
setTimeout(b, 0);
setTimeout(c, 0);
d();
// run order
Queue
a
c (async)
b
c
d
b (async)
Async JavaScript
start();�a();
setTimeout(b, 0);
setTimeout(c, 0);
d();
stop();
// start
a
d
// stop
b // missed!
c // missed!
What if we wanted to time how long this runs?
This won't work:
Async JavaScript with Zone.js
a();
d();
b();
Time
start();
stop();
start();
stop();
c();
start();
stop();
Async JavaScript with Zone.js
a();
d();
b();
Time
beforeTask();
afterTask();
beforeTask();
afterTask();
c();
beforeTask();
afterTask();
Async JavaScript with Zone.js
zone.run(function () {
a();
setTimeout(b, 0);
setTimeout(c, 0);
d();
});
var start, time;
function beforeTask () {
start = Date.now();
}
function afterTask () {
time += (Date.now() - start);
}
What's happening?
Async tasks run in the same zone as where they were registered
registered = setTimeout,
addEventListener,
onclick,
etc.
Transitive
function first () {
setTimeout(second, 0);
}
function second () {
setTimeout(third, 0);
}
function third () { /* ... */ }
zone.run(first);
beforeTask();
first();
afterTask();
beforeTask();
second();
afterTask();
beforeTask();
third();
afterTask();
Time
Zone.js is a meta-monkey patch
Zone.js makes it easy to:
How can I use zones?
Demo
What do zones have to do with Angular?
Let's say (hypothetically) you're making this framework...
What do zones have to do with Angular?
Can we figure out the right time to call��$rootScope.$apply()
so that you never ever have to think about it?
What do zones have to do with Angular?
zone.fork({
afterTask: function () {� angular.digest();� }�}).run(function () {� angular.bootstrap();�});
How are zones useful to me as a user of Angular?
We'll use this for dirty checking in AngularJS version 2.0 and you won't have to worry about it.
$rootScope.apply()
It's on GitHub
Source Code and Demos:
http://github.com/angular/zone.js
Stand-alone ES5 micro-lib (~200 LOC)
You can tell your backbone and ember friends without getting into arguments!
fin