說明:本文的示例程式碼並非 AngularJS 原始碼,而是來自書籍《Build Your Own AngularJs》。作者僅依賴 jQuery 與 lodash,一步步建構出 AngularJS 的各個核心模組,對全面理解框架運作有非常大的幫助。若你正在用 AngularJS 開發,並希望徹底掌握這個工具,相信能帶來不少收穫。
本文希望釐清以下幾項與 scope 相關的機制:
1. 髒檢測(dirty-checking)的核心:$watch 與 $digest;
2. 觸發 $digest 循環的幾種方式:$eval、$apply、$evalAsync、$applyAsync;
3. scope 的繼承機制與隔離 scope;
4. 依賴 scope 的事件循環:$on、$broadcast、$emit。
髒檢測的原理可以一句話概括:scope 透過 $watch 把 watcher 物件放進 $$watchers 陣列;每次 $digest 循環被觸發時,就遍歷這個陣列,執行每個 watcher 的 watchFn 取得當前值,與 watcher 上快取的 last 相比較,若不同就執行 listenerFn。
function Scope() {
this.$$watchers = []; // 監聽器數組
this.$$lastDirtyWatch = null; // 每次digest循環的最後一個髒的watcher, 用於優化digest循環
this.$$asyncQueue = []; // scope上的異步隊列
this.$$applyAsyncQueue = []; // scope上的異步apply隊列
this.$$applyAsyncId = null; //異步apply信息
this.$$postDigestQueue = []; // postDigest執行隊列
this.$$phase = null; // 儲存scope上正在做什麼,值有:digest/apply/null
this.$root = this; // rootScope
this.$$listeners = {}; // 存儲包含自定義事件鍵值對的對象
this.$$children = []; // 存儲當前scope的兒子Scope,以便$digest循環遞歸
}
可見 scope 本質上就是一個普通的 JavaScript 建構函數,用 new 就能實例化。
/* $watch方法:向watchers數組中添加watcher對象,以便對應調用 */
Scope.prototype.$watch = function(watchFn, listenerFn, valueEq) {
var self = this;
watchFn = $parse(watchFn);
// watchDelegate: 針對watch expression是常量和 one-time-binding的情況,進行優化。
// 在第一次初始化之後刪除watch
if(watchFn.$$watchDelegate) {
return watchFn.$$watchDelegate(self, listenerFn, valueEq, watchFn);
}
var watcher = {
watchFn: watchFn,
listenerFn: listenerFn || function() {},
valueEq: !!valueEq,
last: initWatchVal
};
this.$$watchers.unshift(watcher);
this.$root.$$lastDirtyWatch = null;
return function() {
var index = self.$$watchers.indexOf(watcher);
if(index >= 0) {
self.$$watchers.splice(index, 1);
self.$root.$$lastDirtyWatch = null;
}
};
};
三個參數的意義:
watchFn——監視表達式。使用時通常傳入一個 expression,經 $parse 服務處理後回傳監視函式,功能等同 function() { return scope.someValue; }。
listenerFn——監聽函式。當循環偵測到值改變時被呼叫。
valueEq——是否全等監視,預設 false。此時 $watch 做的是「引用監視」:若被監視的是原始型別,能正確發現改變;若是參考型別,由於賦值只是讓變數指向新物件,watcher 快取的 last 仍指向舊物件,於是內部屬性的變化不會被偵測到。要監看物件內部變化就得設為 true,這時每次比較前會用 angular.copy() 深拷貝、再用 angular.equal() 比對。代價很明確:被監視物件越大,效能損耗越明顯,所以要依實際情況取捨。
從程式碼看,$watch 做的事非常單純——組出 watcher 物件、unshift 進陣列、回傳一個用來移除自己的函式。
《Build your own AngularJs》把 $digest 拆成 $$digestOnce 與 $digest 兩個函式,分別對應內層與外層循環。這雖非框架原始碼,但更利於理解。
Scope.prototype.$$digestOnce = function() {
var dirty;
var continueLoop = true;
var self = this;
this.$$everyScope(function(scope) {
var newValue, oldValue;
_.forEachRight(scope.$$watchers, function(watcher) {
try {
if(watcher) {
newValue = watcher.watchFn(scope);
oldValue = watcher.last;
if(!scope.$$areEqual(newValue, oldValue, watcher.valueEq)) {
scope.$root.$$lastDirtyWatch = watcher;
watcher.last = (watcher.valueEq ? _.cloneDeep(newValue) : newValue);
watcher.listenerFn(newValue,
(oldValue === initWatchVal ? newValue : oldValue), scope);
dirty = true;
} else if(scope.$root.$$lastDirtyWatch === watcher) {
continueLoop = false;
return false;
}
}
} catch(e) {
console.error(e);
}
});
return continueLoop;
});
return dirty;
};
核心邏輯就在 $$everyScope 的迴圈體內:遍歷 $$watchers、比對新舊值、決定是否呼叫 listenerFn,並把 newValue、oldValue、scope 三個參數傳進去。
有兩處細節值得注意。第一,第 18 行對 watcher.last 的賦值證實了先前所說 valueEq 的作用——全等模式下存的是深拷貝。第二,第 23 行的判斷是效能優化:既然 $digest 會一直跑到沒有髒值為止,那就快取「上一輪最後一個被判定為髒的 watcher」,下一輪遇到它就可以提前收工,省下大量無效遍歷。
// digest循環的外循環,保持循環直到沒有髒值為止
Scope.prototype.$digest = function() {
var ttl = TTL;
var dirty;
this.$root.$$lastDirtyWatch = null;
this.$beginPhase('$digest');
if(this.$root.$$applyAsyncId) {
clearTimeout(this.$root.$$applyAsyncId);
this.$$flushApplyAsync();
}
do {
while (this.$$asyncQueue.length) {
try {
var asyncTask = this.$$asyncQueue.shift();
asyncTask.scope.$eval(asyncTask.expression);
} catch(e) {
console.error(e);
}
}
dirty = this.$$digestOnce();
if((dirty || this.$$asyncQueue.length) && !(ttl--)) {
this.$clearPhase();
throw TTL + ' digest iterations reached';
}
} while (dirty || this.$$asyncQueue.length);
this.$clearPhase();
while(this.$$postDigestQueue.length) {
try {
this.$$postDigestQueue.shift()();
} catch(e) {
console.error(e);
}
}
};
第 24 行把 $$digestOnce() 的回傳值存進 dirty,do-while 迴圈只要 dirty 為 true 就持續迭代,直到穩定為 false——這就是髒檢測外層循環的全貌。
但有個問題必然會遇到:如果某段 listenerFn 每次執行都改動另一個被監視的值,兩者互相觸發,迴圈將永不收斂。AngularJS 用 TTL(time to live)因應:第 26 行的判斷讓 TTL 每輪遞減,歸零時拋出 10 digest iterations reached,提醒開發者循環不會穩定。這個上限是可以設定的。
要在 scope 的 context 中執行一段表達式,並可傳入 locals 物件覆蓋 context 中的屬性:
Scope.prototype.$eval = function(expr, locals) {
return $parse(expr)(this, locals);
};
補充:$parse 服務接受一個表達式或函式,回傳一個接受 (context, locals) 兩個參數的函式。
Scope.prototype.$apply = function(expr) {
try {
this.$beginPhase('$apply');
return this.$eval(expr);
} finally {
this.$clearPhase();
this.$root.$digest();
}
};
本質上就是「用 $eval 執行表達式,再從 $rootScope 啟動 $digest」。
這也是初學者最常遇到的問題解答:用第三方庫(例如 jQuery 插件、setTimeout、原生 DOM 事件)改動了 scope 上的值,畫面卻沒更新——因為這些回呼不在 AngularJS 的 context 內,$digest 沒有被觸發。$apply 就是為此而生的標準解法。
若確定不需要從 $rootScope 開始,可直接呼叫 scope.$digest() 取代 $apply,只跑當前 scope 及其子 scope,能省下可觀效能。
Scope.prototype.$evalAsync = function(expr) {
var self = this;
if(!self.$$phase && !self.$$asyncQueue.length) {
setTimeout(function() {
if(self.$$asyncQueue.length) {
self.$root.$digest();
}
}, 0);
}
this.$$asyncQueue.push({ scope: this, expression: expr });
};
我們更習慣用 $timeout 做延遲,但 $timeout 會把執行控制權交還瀏覽器——若同時還有 UI 渲染、事件處理、AJAX 回應等任務排隊,實際執行時機就變得不可控。
$evalAsync 的做法是把任務推進 $$asyncQueue,由正在運行的 $digest 循環在每輪開始時消化(見外層循環的 while 區塊);若當前沒有循環在跑,才自己用 setTimeout 補一次 $digest。這樣延遲的時機就嚴格落在框架的節奏裡。
/* 這個方法用於 知道需要在短時間內多次使用$apply的情況,
能夠對短時間內多次$digest循環進行合並,是針對$digest循環的優化策略 */
Scope.prototype.$applyAsync = function(expr) {
var self = this;
self.$$applyAsyncQueue.push(function() {
self.$eval(expr);
});
if(self.$root.$$applyAsyncId === null) {
self.$root.$$applyAsyncId = setTimeout(function() {
self.$apply(_.bind(self.$$flushApplyAsync, self));
}, 0);
}
};
實務上常遇到短時間內連續收到多個 HTTP 回應,每個都觸發一次完整 $digest 的情況。$applyAsync 會把它們合併成一次循環,是明確的效能優化手段。
/* $$postDigest 用於在下一次digest循環後執行函數隊列
不同於applyAsync 和 evalAsync, 它不觸發digest循環 */
Scope.prototype.$$postDigest = function(fn) {
this.$$postDigestQueue.push(fn);
};
它提供「在本輪 digest 結束後執行」的時機,但不會主動啟動循環。前綴 $$ 表示這是框架內部方法,不保證 API 穩定,應用開發中極少使用。
髒檢測的機制說穿了並不複雜:靠 $$watchers 快取監視器,靠 $digest 迴圈反复比對直到收斂,並以 TTL 防止無限迴圈。真正需要建立的是「什麼操作在 AngularJS 的 context 內、什麼不在」的直覺——理解了這一點,多數「資料改了畫面沒動」的問題都能立刻定位。
下一篇將繼續說明 scope 的繼承與隔離機制,以及 $on、$broadcast、$emit 組成的事件系統。