如何在angularjs中手动停止摘要循环 [英] How to stop digest cycle manually in angularjs
问题描述
在摘要循环中,对变量进行脏检查,即是否有100个范围变量,并且如果我更改一个变量,则它将监视所有变量.
As digest cycle do the dirty checking of the variable that is if there are 100 scope variables and if I change one variable then it will run watch of all the variables.
假设我有100个彼此独立的范围模型变量.如果我对一个变量进行了更改,那么我不想检查所有其他99个变量.有什么办法吗?如果是,怎么办?
Suppose I have 100 scope model variables that are independent of each other. If I make changes in one variable then I don't want to check all other 99 variables. Is there any way to do this ? If yes, how ?
推荐答案
令人惊讶的是,这通常不是问题,即使表达式成千上万,即使具有成千上万的绑定,浏览器也不会出现问题. how many watchers are ok to have
的常见答案是 2000
.
Surprisingly, this is usually not a problem, Browsers don’t have problems even with thousands of bindings, unless the expressions are complex. The common answer for how many watchers are ok to have
is 2000
.
解决方案:
从AngularJS 1.3
开始相当容易,因为 one-time
绑定现在已成为核心.
It is fairly easy onwards from AngularJS 1.3
, since one-time
bindings are in core now.
- 一次绑定变量.
我们可以使用一次绑定(::)
指令来防止观察者观察不需要的变量.在这里,变量只能观看一次&之后,它将不会更新该变量.
We can use One time binding(::)
directive to prevent the watcher to watch the unwanted variables. Here, variable will be watch only once & after that it will not update that variable.
- 手动停止摘要循环.
HTML:
<ul ng-controller="myCtrl">
<li ng-repeat="item in Lists">{{lots of bindings}}</li>
</ul>
控制器代码:
app.controller('myCtrl', function ($scope, $element) {
$element.on('scroll', function () {
$scope.Lists = getVisibleElements();
$scope.$digest();
});
});
在 $digest
期间,您仅对Lists
对象的更改感兴趣,而不对单个项目的更改感兴趣.但是,Angular仍会询问每个观察者以进行更改.
During the $digest
, you are only interested in changes to Lists
object, not changes to individual items. Yet, Angular will still interrogate every single watcher for changes.
stop
和pause
摘要的指令:
directive for stop
and pause
the digest:
app.directive('stopDigest', function () {
return {
link: function (scope) {
var watchers;
scope.$on('stop', function () {
watchers = scope.$$watchers;
scope.$$watchers = [];
});
scope.$on('resume', function () {
if (watchers)
scope.$$watchers = watchers;
});
}
};
});
现在,应该更改控制器代码:
<ul ng-controller="listCtrl">
<li stop-digest ng-repeat="item in visibleList">{{lots of bindings}}</li>
</ul>
app.controller('myCtrl', function ($scope, $element) {
$element.on('scroll', function () {
$scope.visibleList = getVisibleElements();
$scope.$broadcast('stop');
$scope.$digest();
$scope.$broadcast('resume');
});
});
参考文档: https://coderwall.com/p/d_aisq/speeding-up-angularjs-s-digest-loop
谢谢.
这篇关于如何在angularjs中手动停止摘要循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!