angular-源码分析之rootScope

$rootScope 到底是啥

出处

在bootstrap函数中会调用injector.invoke,里面用到了rootScope:

1
2
3
4
5
6
7
8
injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
function bootstrapApply(scope, element, compile, injector) {
scope.$apply(function() { //rootScope
element.data('$injector', injector);
compile(element)(scope);
});
}]
);

从之前的文章中我们可以知道$rootScope从$rootScopeProvider.$get方法返回的,那么我们就可以看$rootScopeProvider.$get方法返回了什么。

$RootScopeProvider

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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;
}

Scope.prototype = {
constructor: Scope,
$new: function(isolate, parent) {

},
//$apply方法就是在这定义的
//expr 可以为function
$apply: function(expr) {
try {
beginPhase('$apply');
try {
return this.$eval(expr);
} finally {
clearPhase();
}
} catch (e) {
$exceptionHandler(e);
} finally {
try {
$rootScope.$digest();
} catch (e) {
$exceptionHandler(e);
throw e;
}
}
}
//省略
};
//定义了Scope对象
var $rootScope = new Scope();

//The internal queues. Expose them on the $rootScope for debugging/testing purposes.
var asyncQueue = $rootScope.$$asyncQueue = [];
var postDigestQueue = $rootScope.$$postDigestQueue = [];
var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];

var postDigestQueuePosition = 0;

return $rootScope;
欢迎关注我的公众号:沉迷Spring
显示 Gitment 评论
0%