2017-09-10 45 views
1

我跟随Tero Parviainen的书“构建您自己的angularJS”,并且在讨论$ evalAsync时引入的概念之一时遇到麻烦。

在其中一个例子,他声明了一个守望者,它总是调用$ evalAsync:

​​

眼看例如,我预计消化周期通过观察重复两次,直到停止。在范围的实现中,代码运行直到摘要不脏或队列中不再有$ evalAsyncs。

Scope.prototype.$digest = function() { 
    var ttl = 10; 
    var dirty; 
    this.$$lastDirtyWatch = null; 
    do { 
    while (this.$$asyncQueue.length) { 
     var asyncTask = this.$$asyncQueue.shift(); 
     asyncTask.scope.$eval(asyncTask.expression); 
    } 
    dirty = this.$$digestOnce(); 
    if ((dirty || this.$$asyncQueue.length) && !(ttl--)) { 
     throw '10 digest iterations reached'; 
    } 
    } while (dirty || this.$$asyncQueue.length); 
}; 

如果对于循环中的每次迭代,如果从数组中移出一个asyncTask,那么该循环是如何运行的?不应该因为$$ asyncQueue被清空而停止循环?

希望我明确表示,谢谢大家!

回答

0

通过调用:

scope.$evalAsync(function(scope) { }); 

添加新项asyncQueue

asyncQueue.push({scope: this, expression: expr, locals: locals}); 

因此,通过this.$$asyncQueue.shift();删除任务我们所说的新的迭代酸当量新的消化周期。

不管怎么说守望的正确实施是:

scope.aValue = [1, 2, 3]; 
    scope.$watch(
    function(scope) { 
     return scope.aValue; 
    }, 
    function(newValue, oldValue, scope) { } 
); 
+0

嘿马克西姆!感谢您的回答。据我所知,只有一个摘要循环被触发,但正如你所说,当调用$ evalAsync时,你添加一个新的项目asyncQueue。我没有得到的是为什么这个过程重复一遍又一遍。我在摘要函数的开始处使用console.log,它只调用一次。为什么执行 ''' 函数(范围){} ''' $ eval不断向$$ asyncQueue添加一个项目? 再次感谢和抱歉在理解 – Riboher

+0

@Riboher'我没有得到的是为什么这个过程一遍又一遍地重复。'这就是我所说的'scope。$ evalAsync'将新项目添加到'asyncQueue'和调用新的观察迭代器。新的迭代器再次调用'scope。$ evalAsync',所以这个循环是无限的 –