微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Angular 2中Zone.js的用途是什么?

目前正在学习Angular 2.0,我来到了Zone.js文件,我想知道Zone.js文件的目的是什么,以及它如何使我的应用程序更好。
区域是跨异步任务持久存在的执行上下文,并允许区域的创建者观察和控制区域内代码的执行。

我认为在angular2中使用zonejs的主要目的是知道何时渲染。

根据NgZone Primer(第5章:用例/用例3:框架自动渲染)

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使用区域来修补异步API(addEventListener,setTimeout(),…),并使用来自这些修补API的通知在每次发生某些异步事件时运行更改检测。

对于这个Angular区域有onMicrotaskEmpty事件

https://github.com/angular/angular/blob/2.2.4/modules/%40angular/core/src/zone/ng_zone.ts#L199

和ApplicationRef订阅此事件以触发更改检测(Application.tick)

https://github.com/angular/angular/blob/2.2.4/modules/%40angular/core/src/application_ref.ts#L405-L406

zonejs也可用于调试,测试和分析。如果您遇到一些错误,它可以帮助您查看整个调用堆栈。

区域补丁异步API如:

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

这篇文章可能有助于理解它在angular2中的工作原理

> http://blog.thoughtram.io/angular/2016/02/01/zones-in-angular-2.html
> http://blog.kwintenp.com/how-the-hell-do-zones-really-work/

原文地址:https://www.jb51.cc/angularjs/144011.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐