[英]How can I prevent to watchers from firing in the same digest cycle?
I want to call a function drawChart()
when either my string chartTitle
or when any of the properties in my object chartOptions
changes. 我想在我的字符串
chartTitle
或对象chartOptions
任何属性发生更改时调用函数drawChart()
。
Watching them individually is easy: 单独观看它们很容易:
$scope.$watch('chartTitle', drawChart);
$scope.$watchCollection('chartOptions', drawChart);
However, I need a way to combine them into one $watch
statement (without adding chartTitle
as a property of chartOptions
. 但是,我需要一种方法将它们组合成一个
$watch
的语句(不添加chartTitle
作为一个属性chartOptions
。
How can I prevent both of these watchers from firing in the same digest cycle. 如何防止这两个监视程序在同一摘要周期内触发。 That is, if I change both
chartTitle
and a property on chartOptions
, how can I prevent drawChart
from being called twice? 也就是说,如果我改变都
chartTitle
和财产chartOptions
,我怎么能防止drawChart
被调用两次?
Do a deep watch on chartOptions
and chartTitle
. 深入了解
chartOptions
和chartTitle
。 Unfortunately chartOptions
is an extremely large and complicated object, so doing a deep watch on these properties is infeasible. 不幸的是,
chartOptions
是一个非常大且复杂的对象,因此,对这些属性进行深入监视是不可行的。 Is it possible to put a limit on how deep to go? 可以限制深度吗?
Detect in the chartOptions
watcher whether chartTitle
has been changed during this digest cycle, and vice versa. 检测在
chartOptions
守望者是否chartTitle
已经消化此周期中被改变,反之亦然。 Is this even possible? 这有可能吗?
Figure out a watch expression that would capture all the properties on chartOptions
and chartTitle
. 找出一个监视表达式,该表达式将捕获
chartOptions
和chartTitle
所有属性。
You can make a deep watch: 您可以进行深入了解:
$scope.$watch(
function() {
return {
chartTitle: $scope.chartTitle,
chartOptions: $scope.chartOptions
};
},
function(newval) {
...
},
true // deep watch
);
Keep an eye for performance problems, it will be creating an object each digest cycle. 密切关注性能问题,它将在每个摘要周期创建一个对象。 Normally it won't matter, but for a heavyweight application it might.
通常这并不重要,但是对于重量级的应用程序则可能如此。
Combine chartTitle
and chartOptions
into a single object, then do a $watchCollection
on that object. 将
chartTitle
和chartOptions
组合到一个对象中,然后对该对象执行$watchCollection
。
$scope.$watchCollection(function() {
// Make a shallow clone of all the properties in chartOptions
var amalgam = {};
for (var key in $scope.chartOptions) {
var val = $scope.chartOptions[key];
amalgam[key] = val;
}
// Add the chart title to our shallow clone
amalgam.chartTitle = $scope.chartTitle;
return amalgam;
}, drawChart);
Note this may not be very fast as you are creating a new object every digest cycle. 请注意,这可能不是很快,因为每个摘要周期都在创建一个新对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.