Having a question regarding an article about zone.js
in Angular2+. I was reading an article from blog.angular-university.io. I thought some parts were a bit cryptic and have some questions about it and things I'm not sure if I understand correctly. The article states:
A zone is nothing more than an execution context that survives multiple Javascript VM execution turns.
Does the above statement mean that multiple async callbacks which are stacked in the event queue have one execution context and thus the same value for this
?
It's a generic mechanism which we can use to add extra functionality to the browser. Angular uses Zones internally to trigger change detection.
Angular is changing the async
functions (settimeout
, AJAX, etc) at runtime. Does this mean that besides finishing the callback of the callback also has additional functionality which Angular uses to detect changes
Is my current understanding correct? If not, what's wrong?
Does the above statement mean that multiple async callbacks which are stacked in the event queue have one execution context and thus the same value for this?
No. Consider execution context as simply (oversimplified) an object which is shared by all the codes running in the particular zone. For e.g. During bootstrap, when angular module is getting initialized, Angular creates (forks) a zone called 'angular'. Further, it sets a property 'isAngularZone':true. You can think of it like creating an object in which new property is set. Now, this property will be available to all the code running (or scheduled to run) in Angular, as the same is running in angular zone. However, if you run your code outside angular zone, this property will not be accessible.
Does this mean that besides finishing the callback of the callback also has additional functionality which Angular uses to detect changes
Callback does not have any additional functionality. Its the way Zone.js handles your callback which provides Angular additional capabilities like determining when to kick off change detection cycle. E.g. when you pass callback in setTimeout function, it is wrapped in another function by Zone.js and same is substituted in place of your callback. This is monkey patching API. Now, when JS VM call the Zone.js wrapped callback, it does various operations before actually calling your callback method. One of those operation is to inform the zone (in which that callback was scheduled) of the invocation of the callback. Here, if that zone is 'angular', it will generate events and will kick off change detection cycle.