# Angular zone学习笔记

+关注继续查看

https://blog.thoughtram.io/angular/2016/01/22/understanding-zones.html

foo();
bar();
baz();

function foo() {...}
function bar() {...}
function baz() {...}


var start,
time = 0;
timer = performance ? performance.now : Date.now;

// start timer
start = timer();
foo();
bar();
baz();
// stop timer
time = timer() - start;
// log time in ms
console.log(Math.floor(time*100) / 100 + 'ms');


function doSomething() {
}

// start timer
start = timer();
foo();
setTimeout(doSomething, 2000);
bar();
baz();
// stop timer
time = timer() - start;


Zones can perform an operation - such as starting or stopping a timer, or saving a stack trace - each time that code enters or exits a zone. They can override methods within our code, or even associate data with individual zones.

zone可以在一段代码进入或者离开一个zone的时候，执行一个操作，比如开启或者关闭计时器，或者保存一个堆栈跟踪。

Zones are actually a language feature in Dart.

Zone实际上是编程语言Dart的一个特性。Dart编译之后的代码也是JavaScript，所以我们可以直接在JavaScript里实现Zone的特性。

Angular项目里通常都有zone.js的依赖：

function main() {
foo();
setTimeout(doSomething, 2000);
bar();
baz();
}

zone.run(main);


Zones can perform an operation each time our code enters or exits a zone.

var myZone = zone.fork();

myZone.run(main);


fock的时候可以指定一些参数，定制fock出来的zone的行为：

var myZoneSpec = {
},
}
};

var myZone = zone.fork(myZoneSpec);
myZone.run(main);

// Logs:


It turns out that there are a few other hooks. In fact, those aren’t just hooks, but monkey-patched methods on the global scope.

when we call setTimeout() we actually call Zone.setTimeout(), which in turn creates a new zone using zone.fork() in which the given handler is executed.

And that’s why our hooks are executed as well, because the forked zone in which the handler will be executed, simply inherits from the parent zone.

Zone.js重载了下列方法，并且以hook的方式提供给应用开发人员使用：

Zone.setInterval()

Zone.prompt()

Zone.requestAnimationFrame()

Zone.removeEventListener()

We might wonder why methods like alert() and prompt() are patched as well. As mentioned earlier, those patched methods are hooks at the same time. We can change and extend them by forking a zone exactly the same way we did with beforeTask and afterTask. This turns out to be super powerful, because we can intercept calls to alert() and prompt() and change their behaviour when we write tests.

var profilingZone = (function () {
var time = 0,
timer = performance ?
performance.now.bind(performance) :
Date.now.bind(Date);
return {
this.start = timer();
},
time += timer() - this.start;
},
time: function () {
return Math.floor(time*100) / 100 + 'ms';
},
reset: function () {
time = 0;
}
};
}());


zone
.fork(profilingZone)
.fork({
console.log('Took: ' + zone.time());
}
})
.run(main);


9637 0
Json.Net6.0入门学习试水篇

1130 0

13363 0
+关注
1633

0

+ 订阅

《2021云上架构与运维峰会演讲合集》

《零基础CSS入门教程》

《零基础HTML入门教程》