简介
观察者模式是一种一对多的关系设计方案,一旦有变化发生,所有的订阅者都会响应。
const Event = function() {let clientList = {}let listen = nulllet trigger = nulllet remove = nulllisten = function(key, fn) {const fns = clientList[key]if(!fns) {clientList[key] = []}clientList[key].push(fn)}trigger = function(key, message) {const fns = clientList[key]if(!fns) return falsefor(let i = 0, len = fns.length; i < len; i++) {const fn = fns[i]fn(message)}}remove = function(key, fn) {const fns = clientList[key]if(!fns) return falseif(!fn) {clientList[key] = []} else {for(let i = 0, len = fns.length; i++) {const _fn = fns[i]if(_fn === fn) {fns.splice(i, 1)}}}}return {listen: listen,trigger: trigger,remove: remove}}
Vue中的订阅者模式
订阅者 Dep
class Dep {constructor(){this.subs = []}addSub(sub) {this.subs.push(sub)}notify() {this.subs.forEach(sub => {sub.update()})}}
观察者Watcher
class Watcher {constructor() {Dep.target = this}update() {}}
依赖收集 Observer
function Observer(obj) {Object.keys(obj).forEach(key => {let val = obj[key]const dep = new Dep()Object.defineProperty(obj, key , {enumerable: true,configurable: true,get: function reactiveGetter() {dep.addSub(Dep.target) // 把watch对象存储到dep的subs中return val},set: function(newVal) {if(val === newVal) returnval = newVal// 在set的时候触发更新dep.notify()}})}
