您的位置:首页 > Web前端 > AngularJS

深入理解AngularJs-scope(二)

2017-06-14 16:06 537 查看
深入理解AngularJs-scope(一)中,我们对AngularJs的脏检测及其触发、异步任务队列进行了学习。紧接上一篇文章 深入理解AngularJs-scope(一),我们来看看scope对以下两个特性的实现。

scope的继承机制和 isolated scope;

依赖于scope的事件系统: $on, $broadcast, $emit;

scope的继承机制

  在上一篇文章中,我们创建了scope类,并在scope.prototype上实现了脏检测和异步任务相关的各个方法。

  现在,我们来看看AngularJs中,scope之间是如何通过继承联系在一起的,如何从parentScope上获取properties。实际上,得益于javascript的原型继承机制,要实现scope的继承相当的简单,代码如下:

Scope.prototype.$new = function(isolated, parent) {
var child;
parent = parent || this;

if(isolated) {
child = new Scope();
child.$root = parent.$root;
child.$$asyncQueue = parent.$$asyncQueue;
child.$$postDigestQueue = parent.$$postDigestQueue;
child.$$applyAsyncQueue = parent.$$applyAsyncQueue;
} else {
var ChildScope = function() {};
ChildScope.prototype = this;
child = new ChildScope();
}

parent.$$children.push(child);

child.$$watchers = []; // shadow这个prop,使成为每个scope独立拥有这个prop
child.$$listeners = {}; // shadow这个prop, 存储包含自定义事件键值对的对象
child.$$children = []; // shadow这个prop,使成为每个scope独立拥有这个prop
child.$parent = parent; // 缓存parentScope, 以便让scope上的其他method能够使用它,比如$destroy

return child;
};


  在我们使用AngularJs进行开发时,$new方法的调用无处不在。大部分情况下并不需要我们手动调用,只是指令自己做了创建scope的工作。

  $new方法有两个参数:

    isolated-布尔值,表示新建的scope是不是 isolated scope(孤立的scope)。

    parent-支持传入一个其他scope来作为 AngularJs scope机制中的parentScope。    

  AngularJs中的scope分为两种,一种是普通scope,如上面代码13行所示,普通scope的prototype指向parentScope, 故能够通过原型链获取到parentScope上的properties。

                 另一种是isolated(孤立) scope, isolated是通过 Scope构造函数创建,它的protorype是指向scope构造函数的,并不是parentScope,所以不能从原型链访问parentScope的properties。

  代码19行至22对新scope的$$watchers、$$listeners、$$children、$parent进行了初始化,因为这些属性是每个scope实例自己拥有、自己维护的。

scope的事件系统:订阅/发布

  AngularJs 也为开发者提供了一套事件系统供开发者进行事件的绑定和触发,基于 publish/subscribe 设计模式。其中包含3个核心方法:$on, $emit, $broadcast。

  $on: 在scope上绑定自定义事件,即向scope的$$listeners数组中插入listener回调函数。返回事件销毁函数。

Scope.prototype.$on = function(eventName, listener) {
var listeners = this.$$listeners[eventName];

if(!listeners) {
this.$$listeners[eventName] = listeners = [];
}

listeners.push(listener);

return function(eventName) {
var index = listeners.indexOf(listener);

if(index >= 0) {
listeners[index] = null;
}
};
};


  $emit: 沿着scope -> parentScope 向上发射事件,执行对应的回调函数。

Scope.prototype.$emit = function(eventName) {
var propagationStopped = false;
var event = {
name: eventName,
targetScope: this,
stopPropagation: function() {
propagationStopped = true;
},
preventDefault: function() {
event.defaultPrevented = true;
}
};

//  把event和additionalArgs拼接成新数组,通过apply方法传入listener, 使参数获取方式正常
var listenerArgs = [event].concat(_.tail(arguments));
var scope = this;

do {
event.currentScope = scope;
scope.$$fireEventOnScope(eventName, listenerArgs);
scope = scope.$parent;  // 通过改变scope引用 实现向上传播的关键代码
} while (scope && !propagationStopped);

event.currentScope = null;

return event;
};


   $broadcast: 向下广播事件,并触发对应的回调函数。$broadcast有一点特殊,一旦开始向下广播,就不能中断。

Scope.prototype.$broadcast = function(eventName) {
var event = {
name: eventName,
targetScope: this,
preventDefault: function() {
event.defaultPrevented = true;
}
};

//  把event和additionalArgs拼接成新数组,通过apply方法传入listener, 使参数获取方式正常
var listenerArgs = [event].concat(_.tail(arguments));

this.$$everyScope(function(scope) {
event.currentScope = scope;
scope.$$fireEventOnScope(eventName, listenerArgs);
return true;
});

event.currentScope = null;

return event;
};


这两篇用到的工具函数我都放在后面,由于事件系统的代码比较简单,就不再做过多说明。

工具方法1: $$fileEventOnScope

/*  $emit 和 $broadcast中 提取出的 fire event listener函数
angularjs源码没有这个方法,其中只是重复了这些代码, 本书作者提出了重复代码
*/
Scope.prototype.$$fireEventOnScope = function(eventName, listenerArgs) {

var listeners = this.$$listeners[eventName] || [];
var i = 0;

while(i < listeners.length) {
if(listeners[i] === null) {
listeners.splice(i, 1);
} else {
try {
listeners[i].apply(null, listenerArgs);
} catch(e) {
console.error(e);
}
i++;
}
}

return event;
};


工具方法2: $$everyScope

/* 为使$digest循环能够递归child scope上的watchers的工具方法
这个方法还用于实现$broadcast
*/
Scope.prototype.$$everyScope = function(fn) {
if(fn(this)) {
return this.$$children.every(function(child) {
return child.$$everyScope(fn);
});
} else {
return false;
}
};


总结:

  这两篇文章提供了与scope相关的脏检测,$watch, 异步任务,继承机制,事件系统的代码及一点补充分析。弄明白了这些机制是如何实现的,当你在开发工作中用到这些东西时,一定会多一份自信,多一份游刃有余。希望这两篇文章能够帮助到正在使用angular1.x开发的朋友。如有错误,请不吝指出~!谢谢~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: