1 of 20

Zone.js

Brian Ford ← @briantford

2 of 20

What is Zone.js?

  • Kind of like domains in Node
  • Kind of like thread locals in Java
  • Dart has zones
    • Zone.js is a port of this Dart feature to JavaScript

3 of 20

What is Zone.js?

"It's open-heart surgery on the web browser"

–Miško

4 of 20

What is a Zone?

It's an execution context.

Cool.

execution context

5 of 20

Async JavaScript

// code

a();

setTimeout(b, 0);

setTimeout(c, 0);

d();

// run order

Queue

a

c (async)

b

c

d

b (async)

6 of 20

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:

7 of 20

Async JavaScript with Zone.js

a();

d();

b();

Time

start();

stop();

start();

stop();

c();

start();

stop();

8 of 20

Async JavaScript with Zone.js

a();

d();

b();

Time

beforeTask();

afterTask();

beforeTask();

afterTask();

c();

beforeTask();

afterTask();

9 of 20

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);

}

10 of 20

What's happening?

Async tasks run in the same zone as where they were registered

registered = setTimeout,

addEventListener,

onclick,

etc.

11 of 20

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

12 of 20

Zone.js is a meta-monkey patch

Zone.js makes it easy to:

  • patch and clean up code at the right time
    • even with async tasks
  • compose behaviors

13 of 20

How can I use zones?

  1. Debugging
  2. Testing/mocking
  3. Profiling
  4. ???

14 of 20

Demo

15 of 20

What do zones have to do with Angular?

Let's say (hypothetically) you're making this framework...

16 of 20

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?

17 of 20

What do zones have to do with Angular?

zone.fork({

afterTask: function () {� angular.digest();� }�}).run(function () {� angular.bootstrap();�});

18 of 20

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()

19 of 20

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!

20 of 20

fin