//观察者
class Subject{//被观察者 被观察者中存在观察者
constructor(name){
this.name = name
this.observers = [];//存放全部观察者
this.state = "被观察者心情很好!"
}
//被观察者要提供一个接收观察者的方法
attach(observer){//订阅
this.observers.push(observer);//存放观察者
}
setState(newState){//发布
this.state = newState;
//attach和setState就是发布订阅
//下面的做用是传入最新方法
this.observers.forEach(o => o.update(newState));
}
}
class Observer{//把观察者注册到观察者中
constructor(name){
this.name = name
}
update(newState){
console.log(this.name,",观察到:",newState)
}
}
let sub = new Subject("被观察者")
let o1 = new Observer("观察者1")
let o2 = new Observer("观察者2")
let o3 = new Observer("观察者3")
sub.attach(o1);
sub.attach(o2);
//不会通知o3,由于o3没有注册
sub.setState("被观察者心情很差");//这样须要setState的方法
//这时候观察应该提供一个方法,用来通知全部的观察者状态更新了update()
复制代码
//发布订阅 promise redux
let fs = require('fs')
//发布 -> 中间代理 <- 订阅
//观察者模式 观察者和被观察者,若是被观察者数据改变,通知观察者
let fs = require('fs')
class Events{
constructor(){
this.callbacks = []
this.result = []
}
on(callback){
this.callbacks.push(callback)
}
emit(data){
this.result.push(data)
this.callbacks.forEach(c=>c(this.result))
}
}
let e = new Events();
e.on((arr)=>{
if(arr.length==1){
console.log(arr)
}
})
e.on((arr)=>{
if(arr.length==1){
console.log(arr)
}
})
fs.readFile('./name.txt','utf8',function(err,data){
e.emit(data);
});
fs.readFile('./age.txt','utf8',function(err,data){
e.emit(data);
});
复制代码
#####观察者模式javascript
//建立游戏
class PlayGame{
constructor(name,level){
this.name = name;
this.level = level;
this.observers = [];
}
publish(money){//发布
console.log(this.level + '段位,' + this.name + '寻求帮助')
this.observers.forEach((item)=>{
item(money)
})
}
subscribe(target,fn){//订阅
console.log(this.level + '段位,' + this.name + '订阅了' + target.name)
target.observers.push(fn)
}
}
//建立游戏玩家
let play1 = new PlayGame('play1', '钻石')
let play2 = new PlayGame('play2', '黄金')
let play3 = new PlayGame('play3', '白银')
let play4 = new PlayGame('play4', '青铜')
play1.subscribe(play4, (money)=>{
console.log('钻石play1表示:' + (money >= 500? '' : '暂时很忙,不能') + '给予帮助')
})
play2.subscribe(play4, (money)=>{
console.log('黄金play2表示:' + (money > 200 && money < 500? '' : '暂时很忙,不能') + '给予帮助')
})
play3.subscribe(play4, function(money){
console.log('白银play3表示:' + (money <= 200 && money>100? '' : '暂时很忙,不能') + '给予帮助')
})
play4.publish(500)
复制代码
#####发布订阅模式html
class Game{
constructor(){
this.topics={}
}
subscribe(topic, fn){
if(!this.topics[topic]){
this.topics[topic] = [];
}
this.topics[topic].push(fn);
}
publish(topic, money){
if(!this.topics[topic]) return;
for(let fn of this.topics[topic]){
fn(money)
}
}
}
let game = new Game()
//玩家
class Player{
constructor(name,level){
this.name = name;
this.level = level;
}
publish(topic, money){//发布
console.log(this.level + '猎人' + this.name + '发布了狩猎' + topic + '的任务')
game.publish(topic, money)
}
subscribe(topic, fn){//订阅
console.log(this.level + '猎人' + this.name + '订阅了狩猎' + topic + '的任务')
game.subscribe(topic, fn)
}
}
//建立游戏玩家
let play1 = new Player('play1', '钻石')
let play2 = new Player('play2', '黄金')
let play3 = new Player('play3', '白银')
let play4 = new Player('play4', '青铜')
play1.subscribe('龙', (money) => {
console.log('play1' + (money > 200 ? '' : '不') + '接取任务')
})
play2.subscribe('老虎', (money)=>{
console.log('play2接取任务')
})
play3.subscribe('牛', (money)=>{
console.log('play3接取任务')
})
play4.subscribe('羊', (money)=>{
console.log('play4接取任务')
})
play4.publish('老虎',500)
复制代码
//第一种
var person = new Object();
person.name = "Nicholas";
person.age = 29;
person.job = "Software Engineer";
person.sayName = function(){
alert(this.name);
}
//第二种
var person = {
name: "Nicholas",
age: 29,
job: "Software Engineer",
sayName: function() {
alert(this.name);
}
}
复制代码
####属性描述符:vue
#####数据属性:数据属性包含一个数据值的位置,在这个位置能够读取和写入值java
一、可配置性 [[Configurable]] : 表示可否经过delete删除属性,可否修改属性特性,可否把数据属性修改成访问器属性。
二、可枚举性[[Enumerable]]:表示可否经过for-in循环返回属性。
三、可写入性[[Writable]]:表示可否修改属性值。
四、属性值[[Value]]:表示属性值。
复制代码
#####访问器属性:是包含一对getter和setter函数node
一、可配置性 [[Configurable]]:表示可否经过delete删除属性,可否修改属性特性,可否把访问器属性修改成数据属性。
二、可枚举性[[Enumerable]]:表示可否经过for-in循环返回属性。
三、读取属性函数[[Get]]:在读取属性时调用的函数。
四、写入属性函数[[Set]]:在写入属性时调用的函数。
复制代码
该方法接受三个参数:属性所在对象,属性名字和一个描述符对象
复制代码
这个方法接收两个参数:属性所在对象,属性名字
复制代码
###若是要求对用户的输入进行特殊处理,或者设置属性的依赖关系,就须要用到访问器属性了redux
#####object.defineProperties设计模式
var book = {};
Object.defineProperties(book, {
_year: {
writable:true,
value: 2004
},
edition: {
value: 1
},
year: {
get: function(){
return this._year;
},
set: function(newValue){
console.log("++++",newValue)
if (newValue > 2004) {
this._year = newValue;
this.edition += newValue - 2004;
}
}
}
});
book._year
console.log(book.year)
book.year = 2007
console.log(book.year)
复制代码
#####数据绑定小案例数组
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<input id="input"/></br>
<button id="btn">提交数据</button>
<script> let inputNode = document.getElementById('input'); let person = {} Object.defineProperty(person, 'name' ,{ configurable: true, get: function () { console.log('访问器的GET方法:'+ inputNode.value) return inputNode.value }, set: function (newValue) { console.log('访问器的SET方法:' + newValue) inputNode.value = newValue } }) inputNode.oninput = function () { console.log('输入的值: ' + inputNode.value) person.name = inputNode.value; } let btn = document.getElementById('btn'); btn.onclick = function () { alert(person.name) } </script>
</body>
</html>
复制代码
####MVVM设计模式promise
#####Vue双向绑定的的原理闭包
vue.js 是采用数据劫持结合发布者-订阅者模式的方式,经过Object.defineProperty()来劫持各个属性的setter
getter,在数据变更时发布消息给订阅者,触发相应的监听回调。
具体步骤:
这样作就能够监听到数据的变化。
第一步:
function observe(data) {
if (!data || typeof data !== 'object') {
return;
}
// 取出全部属性遍历
Object.keys(data).forEach(function(key) {
defineReactive(data, key, data[key]);
});
};
function defineReactive(data, key, val){
observe(val); // 监听子属性
Object.defineProperty(data, key, {
enumerable: true, // 可枚举
configurable: false, // 不能再define
get: function() {
return val;
},
set: function(newVal) {
console.log('监听数据变化:', val, ' --> ', newVal);
val = newVal;
}
});
}
var data = {name: '原始数据'};
observe(data);
data.name = '改变数据';
复制代码
/*订阅器*/
//。。。省略
function defineReactive(data, key, val){
var dep = new Dep();//建立订阅器
observer(val);
Object.defineProperty(data, key, {
// 。。。省略
set: function(newVal) {
if(val===newVal) return;
console.log('监听数据变化:', val, ' --> ', newVal);
val = newVal;
dep.notify(); // 通知全部订阅者
}
});
}
function Dep() {
this.subs = [];
}
Dep.prototype = {
addSub: function(sub) {
this.subs.push(sub);
},
notify: function() {
this.subs.forEach(function(sub) {
sub.update();
});
}
};
复制代码
######谁是订阅者?订阅者应该是Watcher, 并且var dep = new Dep();
是在 defineReactive
方法内部定义的,因此想经过dep
添加订阅者,就必需要在闭包内操做,因此咱们能够在 getter
里面动手脚:
/*订阅者*/
// ...省略
Object.defineProperty(data, key, {
get: function() {
// 因为须要在闭包内添加watcher,因此经过Dep定义一个全局target属性,暂存watcher, 添加完移除
Dep.target && dep.addDep(Dep.target);
return val;
}
// ... 省略
});
// Watcher.js
Watcher.prototype = {
get: function(key) {
Dep.target = this;
this.value = data[key]; // 这里会触发属性的getter,从而添加订阅者
Dep.target = null;
}
}
//这里已经实现了一个Observer了,已经具有了监听数据和数据变化通知订阅者的功能
复制代码
function Observer(data) {
this.data = data;
this.walk(data);
}
Observer.prototype = {
constructor: Observer,
walk: function(data) {
var me = this;
Object.keys(data).forEach(function(key) {
me.convert(key, data[key]);
});
},
convert: function(key, val) {
this.defineReactive(this.data, key, val);
},
defineReactive: function(data, key, val) {
var dep = new Dep();
var childObj = observe(val);
Object.defineProperty(data, key, {
enumerable: true, // 可枚举
configurable: false, // 不能再define
get: function() {
if (Dep.target) {
dep.depend();
}
return val;
},
set: function(newVal) {
if (newVal === val) {
return;
}
val = newVal;
// 新的值是object的话,进行监听
childObj = observe(newVal);
// 通知订阅者
dep.notify();
}
});
}
};
function observe(value, vm) {
if (!value || typeof value !== 'object') {
return;
}
return new Observer(value);
};
var uid = 0;
function Dep() {
this.id = uid++;
this.subs = [];
}
Dep.prototype = {
addSub: function(sub) {
this.subs.push(sub);
},
depend: function() {
Dep.target.addDep(this);
},
removeSub: function(sub) {
var index = this.subs.indexOf(sub);
if (index != -1) {
this.subs.splice(index, 1);
}
},
notify: function() {
this.subs.forEach(function(sub) {
sub.update();
});
}
};
Dep.target = null;
复制代码
######compile主要作的事情是解析模板指令,将模板中的变量替换成数据,而后初始化渲染页面视图,并将每一个指令对应的节点绑定更新函数,添加监听数据的订阅者,一旦数据有变更,收到通知,更新视图:
######由于遍历解析的过程有屡次操做dom节点,为提升性能和效率,会先将跟节点el
转换成文档碎片fragment
进行解析编译操做,解析完成,再将fragment
添加回原来的真实dom节点中
function Compile(el) {
this.$el = this.isElementNode(el) ? el : document.querySelector(el);
if (this.$el) {
this.$fragment = this.node2Fragment(this.$el);
this.init();
this.$el.appendChild(this.$fragment);
}
}
Compile.prototype = {
init: function() { this.compileElement(this.$fragment); },
node2Fragment: function(el) {
var fragment = document.createDocumentFragment(), child;
// 将原生节点拷贝到fragment
while (child = el.firstChild) {
fragment.appendChild(child);
}
return fragment;
}
};
复制代码
Compile.prototype = {
// ... 省略
compileElement: function(el) {
var childNodes = el.childNodes, me = this;
[].slice.call(childNodes).forEach(function(node) {
var text = node.textContent;
var reg = /\{\{(.*)\}\}/; // 表达式文本
// 按元素节点方式编译
if (me.isElementNode(node)) {
me.compile(node);
} else if (me.isTextNode(node) && reg.test(text)) {
me.compileText(node, RegExp.$1);
}
// 遍历编译子节点
if (node.childNodes && node.childNodes.length) {
me.compileElement(node);
}
});
},
compile: function(node) {
var nodeAttrs = node.attributes, me = this;
[].slice.call(nodeAttrs).forEach(function(attr) {
// 规定:指令以 v-xxx 命名
// 如 <span v-text="content"></span> 中指令为 v-text
var attrName = attr.name; // v-text
if (me.isDirective(attrName)) {
var exp = attr.value; // content
var dir = attrName.substring(2); // text
if (me.isEventDirective(dir)) {
// 事件指令, 如 v-on:click
compileUtil.eventHandler(node, me.$vm, exp, dir);
} else {
// 普通指令
compileUtil[dir] && compileUtil[dir](node, me.$vm, exp);
}
}
});
}
};
// 指令处理集合
var compileUtil = {
text: function(node, vm, exp) {
this.bind(node, vm, exp, 'text');
},
// ...省略
bind: function(node, vm, exp, dir) {
var updaterFn = updater[dir + 'Updater'];
// 第一次初始化视图
updaterFn && updaterFn(node, vm[exp]);
// 实例化订阅者,此操做会在对应的属性消息订阅器中添加了该订阅者watcher
new Watcher(vm, exp, function(value, oldValue) {
// 一旦属性值有变化,会收到通知执行此更新函数,更新视图
updaterFn && updaterFn(node, value, oldValue);
});
}
};
// 更新函数
var updater = {
textUpdater: function(node, value) {
node.textContent = typeof value == 'undefined' ? '' : value;
}
// ...省略
};
复制代码
######这里经过递归遍历保证了每一个节点及子节点都会解析编译到,包括了{{}}表达式声明的文本节点。指令的声明规定是经过特定前缀的节点属性来标记,如<span v-text="content" other-attr
中v-text
即是指令,而other-attr
不是指令,只是普通的属性。监听数据、绑定更新函数的处理是在compileUtil.bind()
这个方法中,经过new Watcher()
添加回调来接收数据变化的通知
#####完整代码
function Compile(el, vm) {
this.$vm = vm;
this.$el = this.isElementNode(el) ? el : document.querySelector(el);
if (this.$el) {
this.$fragment = this.node2Fragment(this.$el);
this.init();
this.$el.appendChild(this.$fragment);
}
}
Compile.prototype = {
constructor: Compile,
node2Fragment: function(el) {
var fragment = document.createDocumentFragment(),
child;
// 将原生节点拷贝到fragment
while (child = el.firstChild) {
fragment.appendChild(child);
}
return fragment;
},
init: function() {
this.compileElement(this.$fragment);
},
compileElement: function(el) {
var childNodes = el.childNodes,
me = this;
[].slice.call(childNodes).forEach(function(node) {
var text = node.textContent;
var reg = /\{\{(.*)\}\}/;
if (me.isElementNode(node)) {
me.compile(node);
} else if (me.isTextNode(node) && reg.test(text)) {
me.compileText(node, RegExp.$1.trim());
}
if (node.childNodes && node.childNodes.length) {
me.compileElement(node);
}
});
},
compile: function(node) {
var nodeAttrs = node.attributes,
me = this;
[].slice.call(nodeAttrs).forEach(function(attr) {
var attrName = attr.name;
if (me.isDirective(attrName)) {
var exp = attr.value;
var dir = attrName.substring(2);
// 事件指令
if (me.isEventDirective(dir)) {
compileUtil.eventHandler(node, me.$vm, exp, dir);
// 普通指令
} else {
compileUtil[dir] && compileUtil[dir](node, me.$vm, exp);
}
node.removeAttribute(attrName);
}
});
},
compileText: function(node, exp) {
compileUtil.text(node, this.$vm, exp);
},
isDirective: function(attr) {
return attr.indexOf('v-') == 0;
},
isEventDirective: function(dir) {
return dir.indexOf('on') === 0;
},
isElementNode: function(node) {
return node.nodeType == 1;
},
isTextNode: function(node) {
return node.nodeType == 3;
}
};
// 指令处理集合
var compileUtil = {
text: function(node, vm, exp) {
this.bind(node, vm, exp, 'text');
},
html: function(node, vm, exp) {
this.bind(node, vm, exp, 'html');
},
model: function(node, vm, exp) {
this.bind(node, vm, exp, 'model');
var me = this,
val = this._getVMVal(vm, exp);
node.addEventListener('input', function(e) {
var newValue = e.target.value;
if (val === newValue) {
return;
}
me._setVMVal(vm, exp, newValue);
val = newValue;
});
},
class: function(node, vm, exp) {
this.bind(node, vm, exp, 'class');
},
bind: function(node, vm, exp, dir) {
var updaterFn = updater[dir + 'Updater'];
updaterFn && updaterFn(node, this._getVMVal(vm, exp));
new Watcher(vm, exp, function(value, oldValue) {
updaterFn && updaterFn(node, value, oldValue);
});
},
// 事件处理
eventHandler: function(node, vm, exp, dir) {
var eventType = dir.split(':')[1],
fn = vm.$options.methods && vm.$options.methods[exp];
if (eventType && fn) {
node.addEventListener(eventType, fn.bind(vm), false);
}
},
_getVMVal: function(vm, exp) {
var val = vm;
exp = exp.split('.');
exp.forEach(function(k) {
val = val[k];
});
return val;
},
_setVMVal: function(vm, exp, value) {
var val = vm;
exp = exp.split('.');
exp.forEach(function(k, i) {
// 非最后一个key,更新val的值
if (i < exp.length - 1) {
val = val[k];
} else {
val[k] = value;
}
});
}
};
var updater = {
textUpdater: function(node, value) {
node.textContent = typeof value == 'undefined' ? '' : value;
},
htmlUpdater: function(node, value) {
node.innerHTML = typeof value == 'undefined' ? '' : value;
},
classUpdater: function(node, value, oldValue) {
var className = node.className;
className = className.replace(oldValue, '').replace(/\s$/, '');
var space = className && String(value) ? ' ' : '';
node.className = className + space + value;
},
modelUpdater: function(node, value, oldValue) {
node.value = typeof value == 'undefined' ? '' : value;
}
};
复制代码
####实现Watcher
Watcher订阅者做为Observer和Compile之间通讯的桥梁,主要作的事情是: 一、在自身实例化时往属性订阅器(dep)里面添加本身 二、自身必须有一个update()方法 三、待属性变更dep.notice()通知时,能调用自身的update()方法,并触发Compile中绑定的回调,则功成身退
function Watcher(vm, exp, cb) {
this.cb = cb;
this.vm = vm;
this.exp = exp;
// 此处为了触发属性的getter,从而在dep添加本身,结合Observer更易理解
this.value = this.get();
}
Watcher.prototype = {
update: function() {
this.run(); // 属性值变化收到通知
},
run: function() {
var value = this.get(); // 取到最新值
var oldVal = this.value;
if (value !== oldVal) {
this.value = value;
this.cb.call(this.vm, value, oldVal); // 执行Compile中绑定的回调,更新视图
}
},
get: function() {
Dep.target = this; // 将当前订阅者指向本身
var value = this.vm[exp]; // 触发getter,添加本身到属性订阅器中
Dep.target = null; // 添加完毕,重置
return value;
}
};
// 这里再次列出Observer和Dep,方便理解
Object.defineProperty(data, key, {
get: function() {
// 因为须要在闭包内添加watcher,因此能够在Dep定义一个全局target属性,暂存watcher, 添加完移除
Dep.target && dep.addDep(Dep.target);
return val;
}
// ... 省略
});
Dep.prototype = {
notify: function() {
this.subs.forEach(function(sub) {
sub.update(); // 调用订阅者的update方法,通知变化
});
}
};
复制代码
######实例化Watcher
的时候,调用get()
方法,经过Dep.target = watcherInstance
标记订阅者是当前watcher实例,强行触发属性定义的getter
方法,getter
方法执行的时候,就会在属性的订阅器dep
添加当前watcher实例,从而在属性值有变化的时候,watcherInstance就能收到更新通知。
function Watcher(vm, expOrFn, cb) {
this.cb = cb;
this.vm = vm;
this.expOrFn = expOrFn;
this.depIds = {};
if (typeof expOrFn === 'function') {
this.getter = expOrFn;
} else {
this.getter = this.parseGetter(expOrFn.trim());
}
this.value = this.get();
}
Watcher.prototype = {
constructor: Watcher,
update: function() {
this.run();
},
run: function() {
var value = this.get();
var oldVal = this.value;
if (value !== oldVal) {
this.value = value;
this.cb.call(this.vm, value, oldVal);
}
},
addDep: function(dep) {
// 1. 每次调用run()的时候会触发相应属性的getter
// getter里面会触发dep.depend(),继而触发这里的addDep
// 2. 假如相应属性的dep.id已经在当前watcher的depIds里,说明不是一个新的属性,仅仅是改变了其值而已
// 则不须要将当前watcher添加到该属性的dep里
// 3. 假如相应属性是新的属性,则将当前watcher添加到新属性的dep里
// 如经过 vm.child = {name: 'a'} 改变了 child.name 的值,child.name 就是个新属性
// 则须要将当前watcher(child.name)加入到新的 child.name 的dep里
// 由于此时 child.name 是个新值,以前的 setter、dep 都已经失效,若是不把 watcher 加入到新的 child.name 的dep中
// 经过 child.name = xxx 赋值的时候,对应的 watcher 就收不到通知,等于失效了
// 4. 每一个子属性的watcher在添加到子属性的dep的同时,也会添加到父属性的dep
// 监听子属性的同时监听父属性的变动,这样,父属性改变时,子属性的watcher也能收到通知进行update
// 这一步是在 this.get() --> this.getVMVal() 里面完成,forEach时会从父级开始取值,间接调用了它的getter
// 触发了addDep(), 在整个forEach过程,当前wacher都会加入到每一个父级过程属性的dep
// 例如:当前watcher的是'child.child.name', 那么child, child.child, child.child.name这三个属性的dep都会加入当前watcher
if (!this.depIds.hasOwnProperty(dep.id)) {
dep.addSub(this);
this.depIds[dep.id] = dep;
}
},
get: function() {
Dep.target = this;
var value = this.getter.call(this.vm, this.vm);
Dep.target = null;
return value;
},
parseGetter: function(exp) {
if (/[^\w.$]/.test(exp)) return;
var exps = exp.split('.');
return function(obj) {
for (var i = 0, len = exps.length; i < len; i++) {
if (!obj) return;
obj = obj[exps[i]];
}
return obj;
}
}
};
复制代码
######MVVM做为数据绑定的入口,整合Observer、Compile和Watcher三者,经过Observer来监听本身的model数据变化,经过Compile来解析编译模板指令,最终利用Watcher搭起Observer和Compile之间的通讯桥梁,达到数据变化 -> 视图更新;视图交互变化(input) -> 数据model变动的双向绑定效果。
function MVVM(options) {
this.$options = options;
var data = this._data = this.$options.data;
observe(data, this);
this.$compile = new Compile(options.el || document.body, this)
}
//监听的数据对象是options.data,每次须要更新视图,则必须经过
//var vm = new MVVM({data:{name: '原始数据'}});
//vm._data.name = '改变数据'。
//指望的调用方式应该是这样的:
//var vm = new MVVM({data: {name: '原始数据'}}); vm.name = '改变数据';
//须要给MVVM实例添加一个属性代理的方法,使访问vm的属性代理为访问vm._data的属性,改造后的代码以下:
复制代码
//代理
function MVVM(options) {
this.$options = options;
var data = this._data = this.$options.data, me = this;
// 属性代理,实现 vm.xxx -> vm._data.xxx
Object.keys(data).forEach(function(key) {
me._proxy(key);
});
observe(data, this);
this.$compile = new Compile(options.el || document.body, this)
}
MVVM.prototype = {
_proxy: function(key) {
var me = this;
Object.defineProperty(me, key, {
configurable: false,
enumerable: true,
get: function proxyGetter() {
return me._data[key];
},
set: function proxySetter(newVal) {
me._data[key] = newVal;
}
});
}
};
复制代码