angular的ViewModel有一个特地的官方术语叫$scope
, 它只是一个一般组织器(Scope)的实例。换言之,它是一个一般的JS对象。为了完成MVVM框架一般宣扬的那种“转变数据即转变视图”的魔幻效果,它得设备上更多更壮大的外挂。
<div ng-app="myApp" ng-controller="myCtrl">
名: <input type="text" ng-model="firstName"><br>
姓: <input type="text" ng-model="lastName"><br>
<br>
姓名: {{firstName + " " + lastName}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
</script>
app.controller会发作一个$scope
对象, 这个$scope
是传进去的。相当于:
var $scope = new Scope();
$scope.firstName = 'Jane';
$scope.lastName = 'Smith';
相对于avalon将一切vm扁平化地放到avalon.vmodels中,angular则偏向将$scope
对象以树的情势组织起来。
function Scope() {
this.$id = nextUid();
this.$$phase = this.$parent = this.$$watchers =
this.$$nextSibling = this.$$prevSibling =
this.$$childHead = this.$$childTail = null;
this.$root = this;
this.$$destroyed = false;
this.$$listeners = {};
this.$$listenerCount = {};
this.$$watchersCount = 0;
this.$$isolateBindings = null;
}
个中$parent
、$$nextSibling
, $$prevSibling
, $$childHead
, $$childTail
,$root
是指向其他$scope
对象。 $$watchers
是绑定对象的定阅数组,$$watchersCount
是其长度, $$listeners
是松手动触发的函数,$$listenerCount
是其长度。
由于angular是一个一般的JS对象,当属性发作变化时,它本身不能够像avalon那末敏锐地跑去$fire
。 因而它完成了一套庞杂的$fire
要领,但它不叫$fire
, 叫做$digest
。
换言之,avalon的$watch
对应angular的$watch
,另外它另有$watchGroup
, $watchCollection
。avalon的$fire要领对应angular的$digest
, 为了平安,它表面另有$applyAsync
, $apply
, $evalAsync
等几个壳函数。它们配合组成angular的监控体系。$watch
和$digest
是相辅相成的。二者一同,组成了angular作用域的中心功用:数据变化的相应。
先看$watch
要领, 传参比avalon庞杂多,但效果都是返回一个移除监听的函数:
Scope.prototype.$watch: function(watchExp, listener, objectEquality, prettyPrintExpression) {
//将表达式转换为求值函数
var get = $parse(watchExp);
if (get.$$watchDelegate) {
return get.$$watchDelegate(this, listener, objectEquality, get, watchExp);
}
var scope = this,
//一切绑定对象都放在一个数组中,因而存在机能题目
array = scope.$$watchers,
//构建绑定对象
watcher = {
fn: listener,//革新函数
last: initWatchVal,//旧值
get: get,//求值函数
exp: prettyPrintExpression || watchExp,//表达式
eq: !!objectEquality// 比较要领
};
lastDirtyWatch = null;
if (!isFunction(listener)) {
watcher.fn = noop;
}
if (!array) {
array = scope.$$watchers = [];
}
array.unshift(watcher);
incrementWatchersCount(this, 1);
return function deregisterWatch() {//移除绑定对象
if (arrayRemove(array, watcher) >= 0) {
incrementWatchersCount(scope, -1);
}
lastDirtyWatch = null;
};
},
而$digest则庞杂多了,我们先完成它的一个简化版,遍历其一切绑定对象,实行其革新函数。
Scope.prototype.$digest = function() {
var list = this.$$watchers || []
list.forEach(function(watch) {
var newValue = watch.get()
var oldValue = watch.last;
if (newValue !== oldValue) {
watch.fn(newValue, oldValue, self);
}
watch.last = newValue;
})
}
到目前为止,它的逻辑与 avalon的一样,但要邃晓一点,avalon的监控是智能的,如果更新A属性,致使了B属性也发作变化,那末avalon也立刻更新B触及的视图。而angular的$$watcher
内里都是一个个一般对象,如果内里有A,B两个对象。先实行A,A值没有变化,再实行B,B变化了,但B在变化时的同时,也修正了A值。但这时刻,轮回已终了。B触及的视图更改 ,A没有更改,这就分歧理了。因而,我们需要在某个绑定对象发作了一次修正后,再从新检测这个数组。
我们把如今的$digest
函数改名为$$digestOnce
,它把一切的监听器运转一次,返回一个布尔值,示意是不是另有变动了:
Scope.prototype.$$digestOnce = function() {
var self = this;
var dirty;
_.forEach(this.$$watchers, function(watch) {
var newValue = watch.get();
var oldValue = watch.last;
if (newValue !== oldValue) {
watch.fn(newValue, oldValue, self);
dirty = true;
}
watch.last = newValue;
});
return dirty;
};
然后,我们从新定义$digest
,它作为一个“外层轮回”来运转,当有变动发作的时刻,挪用$$digestOnce
:
Scope.prototype.$digest = function() {
var dirty;
do {
dirty = this.$$digestOnce();
} while (dirty);
};
$digest
如今最少运转每一个监听器一次了。如果第一次运转完,有监控值发作变动了,标记为dirty,一切监听器再运转第二次。这会一向运转,直到一切监控的值都不再变化,悉数局势稳固下来了。
但这内里有一个风险,比方A的求值函数里会修正B, B的求值函数又修正A,那末人人都没法稳固下来,不停死轮回。因而我们得把digest的运转控制在一个可接受的迭代数目内。如果这么屡次以后,作用域还在变动,就英勇松手,宣告它永久不会稳固。在这个点上,我们会抛出一个异常,由于不论作用域的状况变成如何,它都不太多是用户想要的效果。
迭代的最大值称为TTL(short for Time To Live)。这个值默许是10,能够有点小(我们刚运转了这个digest 不计其数次),然则记着这是一个机能敏感的处所,由于digest常常被实行,而且每一个digest运转了一切的监听器。
Scope.prototype.$digest = function() {
var ttl = 10;
var dirty;
do {
dirty = this.$$digestOnce();
if (dirty && !(ttl--)) {
throw "10 digest iterations reached";
}
} while (dirty);
};
但这只是模拟了angular的$digest
的冰山一角,可见没有接见器属性
这高阶魔法,想完成MVVM是异常贫苦与庞杂,而且用户运用起来也别扭。
有关$digest
的源码与处置惩罚可见这里
https://github.com/angular/an…
http://www.cnblogs.com/xuezhi…
我们再看$digest 是怎样与angular的ng-model 关联在一同。
ng-model指令有一个$post
要领,它在内里举行绑定事宜,如果用户供应了updateOn这个选项,选项是一些事宜名,那末它就为元素绑定对应的事宜,不然就绑定blur要领
post: function ngModelPostLink(scope, element, attr, ctrls) {
var modelCtrl = ctrls[0];
if (modelCtrl.$options.getOption('updateOn')) {
element.on(modelCtrl.$options.getOption('updateOn'), function(ev) {
modelCtrl.$$debounceViewValueCommit(ev && ev.type);
});
}
function setTouched() {
modelCtrl.$setTouched();
}
element.on('blur', function() {
if (modelCtrl.$touched) return;
if ($rootScope.$$phase) {
scope.$evalAsync(setTouched);
} else {
scope.$apply(setTouched);
}
});
}
我们先看blur的回调,内里$evalAsync
与$apply
要领,它们内里就会挪用$digest
,举行脏检测。
$evalAsync: function(expr, locals) {
if (!$rootScope.$$phase && !asyncQueue.length) {
$browser.defer(function() {
if (asyncQueue.length) {
$rootScope.$digest();
}
});
}
//...略
},
$apply: function(expr) {
try {
beginPhase('$apply');
//...略
} finally {
try {
$rootScope.$digest();
} catch (e) {
$exceptionHandler(e);
throw e;
}
}
},
再看$$debounceViewValueCommit
要领,内里也有一个$apply
要领。换言之,异曲同工,悉数汇在$digest
内里处置惩罚。
但如果许多处所同时发作转变,会不会将它搞死呢?不会,我们注意一下$digest
的源码最上方有一句 beginPhase('$digest')
,临结束时也有一句clearPhase()
。$apply
内里也是 beginPhase('$apply')
与clearPhase()
,它们标识这个$scope对象举行脏检测,直接抛错。
function beginPhase(phase) {
if ($rootScope.$$phase) {
throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
}
$rootScope.$$phase = phase;
}
function clearPhase() {
$rootScope.$$phase = null;
}
但$apply
会将毛病catch住,不让它影响顺序继承运转。这就是官方推我们运用$apply
驱动顺序运转,而不直接用$digest
的原因。
经由过程上面的剖析,avalon与angular的设想重点是差别的,avalon是忙于挖掘言语特性,经由过程接见器中的setter与getter将其谁人简朴的观察者形式放进去。angular则忙于构建其庞杂非常的观察者形式(本节没有展示其全貌,它除了$$watchers行列,另有asyncQueue行列,postDigestQueue行列,applyAsyncQueue行列), 而且为了diff新旧值的差别,发展出一套名叫脏检测的机制。
from 《javascript框架设想》第三版,敬请期待