$watch 'miss' 可以吗? [英] Can $watch 'miss'?
问题描述
我们有以下指令:
app.directive("counterWidget",function(){
return{
restrict:"E",
scope:{
startnumber: '=',
resetter: '='
},
link:function(scope,elem,attr){
scope.f = attr.startnumber;
scope.add = function(){
scope.f++
}
scope.remove = function(){
scope.f--
}
scope.reset = function(){
scope.f = attr.startnumber
scope.$parent.triggerReset()
}
scope.$watch(function(attr) {
return attr.resetter
},
function(newVal) {
if (newVal === true) {
scope.f = attr.startnumber;
}
})
},
template:"<button ng-click='add()'>more</button>"+
"{{f}}"+
"<button ng-click='remove()'>less</button> "+
"<button ng-click='reset()'>reset</button><br><br>"
}
})
在这个指令中有一个监视函数,它监视重置器属性的变化.该属性由控制器中的此函数触发:
In this directive there is a watch function, which watches the resetter attribute for changes. That attribute is triggered by this function in the controller:
$scope.triggerReset = function () {
$scope.reset = true;
console.log('reset')
$timeout(function() {
$scope.reset = false;
},100)
}
问题来了 - $watch 'miss' 可以吗?如果超时时间太短,或者......我不知道......其他原因导致它因某种原因挂断,它是否无法捕捉切换?
The question came up - can $watch 'miss'? If the timeout is too short, or...I don't know...something else causes it to hangup for some reason, can it fail to catch the toggle?
我有以下演示:Plunker
I have the following demo: Plunker
我将超时设置为 1 毫秒,甚至将其全部删除,但它仍然可以正常重置.但是会出现 $watch 变得不可靠的情况吗?
I set the timeout to 1ms, and even removed it all together and it still resets fine. But can some situation arise where a $watch would become unreliable?
推荐答案
没有.您甚至可以将其设置为 0ms,它仍然会捕获.
No. You can even set it to 0ms, and it will still catch.
$timeout
将始终导致其函数内部的代码在与当前循环不同的 $digest
循环中运行.
$timeout
will always cause the code internal to its function to run in a different $digest
cycle from the current one.
$evalAsync
,另一方面,根据情况可能会导致未命中.
$evalAsync
, on the other hand, may cause a miss depending on the circumstances.
有关更多详细信息,请参阅此答案:https://stackoverflow.com/a/16066461/624590
See this answer for more details: https://stackoverflow.com/a/16066461/624590
我错过了一个边缘情况,其中第三个参数被传递给 $timeout
函数.如果您调用 $timeout(fn, 50, false)
(注意末尾的 false
),它将跳过 $apply
步骤并让你错过"改变.这是基于 $timeout
源代码:https://github.com/angular/angular.js/blob/master/src/ng/timeout.js#L64
I missed an edge-case to this where a third parameter is passed to the $timeout
function. If you call $timeout(fn, 50, false)
(notice the false
at the end), it will skip the $apply
step and allow you to "miss" the change. This is based on the $timeout
source code: https://github.com/angular/angular.js/blob/master/src/ng/timeout.js#L64
这篇关于$watch 'miss' 可以吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!