A zone is an execution context that persists across async tasks, and allows the creator of the zone to observe and control execution of the code within the zone.
I think that the main purpose of using zonejs in angular2 is to know when to render.
According to NgZone Primer (Chapter 5: Use Cases/Use Case 3: Framework Auto Render)
Frameworks, such as Angular, need to know when all of the application
work has completed and perform DOM update before the host environment
performs the pixel rendering. In practice this means that the
framework is interested when the main task and the associated micro
tasks have executed but before the VM hands over the control to the
host.
Angular uses the zone to patch async APIs(addEventListener, setTimeout(), ...) and uses notifications from these patched APIs to run change detection every time some async event happened.
For this Angular zone has onMicrotaskEmpty
event
https://github.com/angular/angular/blob/2.2.4/modules/%40angular/core/src/zone/ng_zone.ts#L199
and ApplicationRef
subscribes to this event to trigger change detection (Application.tick
)
https://github.com/angular/angular/blob/2.2.4/modules/%40angular/core/src/application_ref.ts#L405-L406
Also zonejs is useful for debugging, testing, profiling. It helps you see whole call stack if you face with some error.
Zone patches async APIs like:
Promise
XHR
fetch
Error
addEventListener
removeEventListener
FileReader
WebSocket
MutationObserver
WebKitMutationObserver
document.registerElement
navigator.geolocation.getCurrentPosition
navigator.geolocation.watchPosition
copy cut paste abort blur focus canplay canplaythrough change click contextmenu
dblclick drag dragend dragenter dragleave dragover dragstart drop
durationchange emptied ended input invalid keydown keypress keyup
load loadeddata loadedmetadata loadstart message
mousedown mouseenter mouseleave mousemove mouseout mouseover mouseup
pause play playing progress ratechange reset scroll
seeked seeking select show stalled submit suspend
timeupdate volumechange waiting
mozfullscreenchange mozfullscreenerror mozpointerlockchange
mozpointerlockerror error webglcontextrestored webglcontextlost webglcontextcreationerror
setTimeout/clearTimeout
setInterval/clearInterval
setImmediate/clearImmediate
requestAnimationFrame/cancelAnimationFrame
mozRequestAnimationFrame/mozCancelAnimationFrame
webkitRequestAnimationFrame/webkitCancelAnimationFrame
alert
prompt
confirm
This articles might be usefull to understand how it works in angular2
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…