You may have heard that Angular uses zone.js
, but why does Angular use zone.js
, and what features does it provide? Today we will write a separate article to talk about zone.js
, about its role in the Angular framework will be described in the next article.
What is a Zone? The official documentation explains it this way: A Zone is an execution context that spans multiple asynchronous tasks. In one sentence, Zone has a particularly powerful ability to intercept or track asynchronous tasks. Below we will demonstrate its capabilities through an example and briefly analyze the working principle behind it.
<button id="b1">Bind Error</button>
<button id="b2">Cause Error</button>
<script>
function main() {
b1.addEventListener('click', bindSecondButton);
}
function bindSecondButton() {
b2.addEventListener('click', throwError);
}
function throwError() {
throw new Error('aw shucks');
}
main();
</script>
This is a simple HTML page. When the page loads, a click event will be added to the first button, the function of the click event function is to add a click event to the second button, and the function of the click event function of the second button is to throw an exception. We click the first button and the second button in turn, and the console displays the following:
(索引):26 Uncaught Error: aw shucks
at HTMLButtonElement.throwError ((索引):26:13)
But if we start the running code through zone.js
, what will the console output be different, let's adjust the startup code first:
Zone.current.fork(
{
name: 'error',
onHandleError: function (parentZoneDelegate, currentZone, targetZone, error) {
console.log(error.stack);
}
}
).fork(Zone.longStackTraceZoneSpec).run(main);
At this point the console output is as follows:
Error: aw shucks
at HTMLButtonElement.throwError ((索引):26:13)
at ZoneDelegate.invokeTask (zone.js:406:31)
at Zone.runTask (zone.js:178:47)
at ZoneTask.invokeTask [as invoke] (zone.js:487:34)
at invokeTask (zone.js:1600:14)
at HTMLButtonElement.globalZoneAwareCallback (zone.js:1626:17)
at ____________________Elapsed_571_ms__At__Mon_Jan_31_2022_20_09_09_GMT_0800_________ (localhost)
at Object.onScheduleTask (long-stack-trace-zone.js:105:22)
at ZoneDelegate.scheduleTask (zone.js:386:51)
at Zone.scheduleTask (zone.js:221:43)
at Zone.scheduleEventTask (zone.js:247:25)
at HTMLButtonElement.addEventListener (zone.js:1907:35)
at HTMLButtonElement.bindSecondButton ((索引):23:10)
at ZoneDelegate.invokeTask (zone.js:406:31)
at Zone.runTask (zone.js:178:47)
at ____________________Elapsed_2508_ms__At__Mon_Jan_31_2022_20_09_06_GMT_0800_________ (localhost)
at Object.onScheduleTask (long-stack-trace-zone.js:105:22)
at ZoneDelegate.scheduleTask (zone.js:386:51)
at Zone.scheduleTask (zone.js:221:43)
at Zone.scheduleEventTask (zone.js:247:25)
at HTMLButtonElement.addEventListener (zone.js:1907:35)
at main ((索引):20:10)
at ZoneDelegate.invoke (zone.js:372:26)
at Zone.run (zone.js:134:43)
By comparison, we know that when zone.js
is not introduced, we can only know through the error call stack that the exception is thrown by the click function of button 2. After the introduction of zone.js
, we not only know that the exception is thrown by the click function of button 2, but also know that its click function is bound by the click function of button 1, and even know that the first application startup is triggered by the main
function. This ability to continuously track multiple asynchronous tasks is extremely important in large and complex projects, and now let's see how zone.js
does it.
zone.js
takes over the asynchronous APIs provided by the browser, such as click events, timers, etc. It is precisely because of this that it can have stronger control and intervention capabilities for asynchronous operations and provide more capabilities. Now let's take the click event as an example and see how it does it.
proto[ADD_EVENT_LISTENER] = makeAddListener(nativeAddEventListener,..)
In the above code, proto
refers to EventTarget.prototype
, which means that this line of code redefines the addEventListener
function. Let's move on to see what the makeAddListener
function does.
function makeAddListener() {
......
// 关键代码1
nativeListener.apply(this, arguments);
......
// 关键代码2
const task = zone.scheduleEventTask(source, ...)
......
}
This function mainly does two things. One is to execute the addEventListener
function provided by the browser itself in the custom function, and the other is to arrange an event task for each click function zone.js
Key factor.
Now let's go back to the example at the beginning of this article and see why the console can output a complete and complete function call stack. We just analyzed the makeAddListener
function, which mentioned that it arranges an event task for each click function, which is the execution of the zone.scheduleEventTask
function. This schedule event task function actually executes onScheduleTask
in the end:
onScheduleTask: function (..., task) {
const currentTask = Zone.currentTask;
let trace = currentTask && currentTask.data && currentTask.data[creationTrace] || [];
trace = [new LongStackTrace()].concat(trace);
task.data[creationTrace] = trace;
}
The complete function call stack output by the console at the beginning of the article is stored in currentTask.data[creationTrace]
, which is an array of LongStackTrace
instances. Every time an asynchronous task occurs, the onScheduleTask
function will store and record the current function call stack. Let's look at the constructor of the class LongStackTrace
to know:
class LongStackTrace {
constructor() {
this.error = getStacktrace();
this.timestamp = new Date();
}
}
function getStacktraceWithUncaughtError() {
return new Error(ERROR_TAG);
}
this.error
stores the function call stack. getStacktrace
function usually calls the getStacktraceWithUncaughtError
function. When we see new Error
, we can probably know how the entire call stack is obtained.
This article analyzes only an example of the capabilities of zone.js
. If you want to know more about the capabilities, you can refer to the official documentation. Through this example, I hope readers can have a general understanding of zone.js
, because it is also an indispensable cornerstone of Angular change detection. I will cover this in the next article. Welcome to my personal WeChat public account [Zhu Yujie's blog], and I will bring more front-end knowledge sharing in the future.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。