当前位置: 移动技术网 > IT编程>脚本编程>AngularJs > Angularjs全局变量被作用域监听的正确姿势

Angularjs全局变量被作用域监听的正确姿势

2018年06月17日  | 移动技术网IT编程  | 我要评论
如果你只想知道结论: $scope.$watch($rootscope.xxx,function(newval,oldval){ //do something

如果你只想知道结论:

$scope.$watch($rootscope.xxx,function(newval,oldval){
//do something
})

马上就有人问为什么不是:

$rootscope.$watch("xxx",function(newval,oldval){
//do something
})

从我最近的一个bug来说说为什么要用第一种方式。

逻辑如图,一开始我使用了 $rootscope.$watch 的写法。因为 angularjs 在 $rootscope 上的 watch 一旦注册全局有效。而我的这个全局变量恰好是订单信息,也就是说不同的 controller 对他都是有改动的,每一次改动就会触发 $rootscope.$watch 进入别的 controller。可以类比看一下 $rootscope 上的 $broadcast 会全局出发的。

其实这并不是唯一的方式,查一下angular 源码不难找到 watch 方法源码不分有如下代码:

return function deregisterwatch() {
if (arrayremove(array, watcher) >= 0) {
incrementwatcherscount(scope, -1);
}
lastdirtywatch = null;
};

这段代码告诉我们,手动清理 watch 是可行的。例如:

var watcher = $rootscope.$watch("xxx",function(){});
//手动清除 watcher 
watcher();

还是很简单对吧,以上方法同样可以用于 scope 上的 watch。

研究到这里的时候,觉得有点问题,那我在 $scope 会被清理么?于是呼,继续翻源码,我在 $destroy 方法里面找到如下代码:

// disable listeners, watchers and apply/digest methods
this.$destroy = this.$digest = this.$apply = this.$evalasync = this.$applyasync = noop;
this.$on = this.$watch = this.$watchgroup = function() { 
return noop; 
};
this.$$listeners = {};

以上代码是本文给大家介绍的angularjs全局变量被作用域监听的正确姿势,希望大家有所帮助,本文写的不好还请各位大侠多多指教。

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网