[Angular] USING ZONES IN ANGULAR FOR BETTER PERFORMANCE
Zone detects any async opreations. Once an async oprations happens in Angular, Zone will notify change detection to kick in.
Images we have 5000 svg box displaying on the screen.
And each svg elements and three event listener on it:
@Component({
...
template: `
<svg (mousedown)="mouseDown($event)"
(mouseup)="mouseUp($event)"
(mousemove)="mouseMove($event)"> <svg:g box *ngFor="let box of boxes" [box]="box">
</svg:g> </svg>
`
})
class AppComponent {
...
}
Three (3) event handlers are bound to the outer SVG element. When any of these events fire and their handlers have been executed then change detection is performed. In fact, this means that Angular will run change detection, even when we just move the mouse over the boxes without actually dragging a single box!
Since 'mousemove' is the event cause the change detection which is not necessary. So we simple remove it from the HTML:
<svg (mousedown)="mouseDown($event)"
(mouseup)="mouseUp($event)"> <svg:g box *ngFor="let box of boxes" [box]="box">
</svg:g> </svg>
So now we need a way to attach 'mousemove' event for only the selected svg box. We can do this inside 'mousedown' event:
constructor(private zone: NgZone) {} mouseDown(event) {
...
this.element = event.target; this.zone.runOutsideAngular(() => {
window.document.addEventListener('mousemove', this.mouseMove.bind(this));
});
}
We inject NgZone
and call runOutsideAngular()
inside our mouseDown()
event handler, in which we attach an event handler for the mousemove
event. This ensures that the mousemove
event handler is really only attached to the document when a box is being selected.
mouseMove(event) {
event.preventDefault();
this.element.setAttribute('x', event.clientX + this.clientX + 'px');
this.element.setAttribute('y', event.clientX + this.clientY + 'px');
}
In addition, we save a reference to the underlying DOM element of the clicked box so we can update its x
and y
attributes in the mouseMove()
method. We’re working with the DOM element instead of a box object with bindings for x
and y
, because bindings won’t be change detected since we’re running the code outside Angular’s Zone. In other words, we do update the DOM, so we can see the box is moving, but we aren’t actually updating the box model (yet).
In the next step, we want to make sure that, whenever we release a box (mouseUp
), we update the box model, plus, we want to perform change detection so that the model is in sync with the view again. The cool thing about NgZone
is not only that it allows us to run code outside Angular’s Zone, it also comes with APIs to run code inside the Angular Zone, which ultimately will cause Angular to perform change detection again. All we have to do is to call NgZone.run()
and give it the code that should be executed.
Here’s the our updated mouseUp()
event handler:
@Component(...)
export class AppComponent {
...
mouseUp(event) {
// Run this code inside Angular's Zone and perform change detection
this.zone.run(() => {
this.updateBox(this.currentId, event.clientX + this.offsetX, event.clientY + this.offsetY);
this.currentId = null;
}); window.document.removeEventListener('mousemove', this.mouseMove);
}
}
Also notice that we’re removing the event listener for the mousemove
event on every mouseUp. Otherwise, the event handler would still be executed on every mouse move. In other words, the box would keep moving even after the finger was lifted, essentially taking the drop part out of drag and drop. In addition to that, we would pile up event handlers, which could not only cause weird side effects but also blows up our runtime memory.
Notice:
However, we shouldn’t forget that this solution also comes with a couple (probably fixable) downsides. For example, we’re relying on DOM APIs and the global window
object, which is something we should always try to avoid. If we wanted to use this code with on the server-side then direct access of the window variable would be problematic. We will discus these server-side specific issues in a future article. For the sake of this demo, this isn’t a big deal though.
[Angular] USING ZONES IN ANGULAR FOR BETTER PERFORMANCE的更多相关文章
- Angular学习笔记:Angular CLI
定义 Angular CLI:The Angular CLI is a command line interface tool that can create a project, add files ...
- angular enter事件,angular回车事件
angular回车键搜索,angular enter搜索 对于搜索框,用户在输入内容后的搜索习惯不是鼠标点击搜索按钮,而是直接按enter键,那我们怎么给enter键绑定事件呢,其实很简单,代码如下: ...
- Angular 2 升级到 Angular 5
Angular 2 升级到 Angular 5 ts文件最上面的import语句里不要添加 .ts 后缀 , 不然 npm start 编译会失败 . 虽然浏览器能打开项目的URL , 但是内容会丢失 ...
- Angular系列一:Angular程序架构
Angular程序架构 Angular程序架构 组件:一段带有业务逻辑和数据的Html服务:用来封装可重用的业务逻辑指令:允许你向Html元素添加自定义行为模块: 环境搭建 安装nodeJs安装好no ...
- Angular企业级开发(3)-Angular MVC实现
1.MVC介绍 Model-View-Controller 在20世纪80年代为程序语言Smalltalk发明的一种软件架构.MVC模式的目的是实现一种动态的程序设计,使后续对程序的修改和扩展简化,并 ...
- 30行代码让你理解angular依赖注入:angular 依赖注入原理
依赖注入(Dependency Injection,简称DI)是像C#,java等典型的面向对象语言框架设计原则控制反转的一种典型的一种实现方式,angular把它引入到js中,介绍angular依赖 ...
- angular源码分析:angular中脏活累活承担者之$parse
我们在上一期中讲 $rootscope时,看到$rootscope是依赖$prase,其实不止是$rootscope,翻看angular的源码随便翻翻就可以发现很多地方是依赖于$parse的.而$pa ...
- 精通 Angular JS 第一天——Angular 之禅
简介 Angular JS是采用JavaScript语言编写的客户端MVC框架,它为业界带了重大的变化,包括对模板化的创新实现,以及数据的双向绑定,这些特性使得它强大而易用.它可以用来帮助开发者编写单 ...
- [Angular 2] Create Shareable Angular 2 Components
Components that you use across multiple applications need to follow a module pattern that keeps them ...
随机推荐
- [Node & Tests] Intergration tests for Authentication
For intergration tests, always remember when you create a 'mass' you should aslo clean up the 'mass' ...
- winform程序,备份数据库+并压缩+并删除以前的备份
说明:为了定时备份服务器上的数据库并压缩到指定目录,方便下载到本地而写本程序.配合windows的任务计划,可以达到定时备份数据库的目的. 程序需引用SQLDMO.DLL,如电脑上已安装sqlserv ...
- Android 6.0 最简单的权限获取方法 RxPermition EasyPermition
Android 6.0 要单独的获取权限 这里提供两种很简单的方法 EasyPermition RxPermition EasyPermition https://github.com/googles ...
- CMake - SWIG - 移植动态库
CMake - SWIG 最后更新日期:2014-04-25 bykagula 阅读前提:<CMake入门(二)>.<同Java的混合编程-SWIG>.Linux的基本操作.j ...
- Codeforces #28 C.Bath Queue (概率dp)
Codeforces Beta Round #28 (Codeforces format) 题目链接: http://codeforces.com/contest/28/problem/C 题意: 有 ...
- (转)Oracle EXP-00091解决方法
转自:http://blog.csdn.net/dracotianlong/article/details/8270136 EXP-: 正在导出有问题的统计信息. . . 正在导出表 WF_GENER ...
- BP神经网络公式推导及实现(MNIST)
BP神经网络的基础介绍见:http://blog.csdn.net/fengbingchun/article/details/50274471,这里主要以公式推导为主. BP神经网络又称为误差反向传播 ...
- 【剑指offer】对面和相等的正方体
转载请注明出处:http://blog.csdn.net/ns_code/article/details/26509459 剑指offer上的全排列相关题目. 输入一个含有8个数字的数组.推断有么有可 ...
- 程序员的底色(IDE color scheme、CLI 命令行界面)
1. IDE ⇒ Dracula(吸血鬼) IDE:PyCharm,VS2013: sublime:color scheme,Monokai: 2. CLI 命令行界面 $ setterm -inve ...
- Asp.NETCore让FromServices回来
起因 这两天,我忽然有点怀念 Asp.NET MVC 5 之前的时代,原因是我看到项目里面有这么一段代码(其实不止一段,几乎每个 Controller 都是) [Route("home&qu ...