微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

angular的ViewModel设计

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,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,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框架设计》第三版,敬请期待

原文地址:https://www.jb51.cc/angularjs/148808.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐