//觀察者
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;
}
});
}
};
複製代碼