发布订阅
class EventTarget {
constructor () {
this.handlers = {};
}
on (type, handler) {
if (typeof this.handlers[type] === 'undefined') {
this.handlers[type] = []
}
this.handlers[type].push(handler)
}
emit (type, ...args) {
if (this.handlers[type]) {
this.handlers[type].forEach( handler =>{
handler(...args)
})
}
}
off (type, handler) {
if (this.handlers[type]) {
let i = this.handlers[type].findIndex( item => item === handler)
if (i !== -1){
this.handlers[type].splice(i, 1)
}
if (this.handlers[type].length === 0) {
delete this.handlers[type]
}
}
}
offAll (type) {
if (this.handlers[type]) {
delete this.handlers[type]
}
}
}
const target = new EventTarget()
function handleMessage (message) {
console.log('Message Receive: ', message)
}
target.on('message', handleMessage)
target.emit('message', '吃饭了')
const toBeRemovedListener = function() { console.log('我是一个可以被移除的监听者') }
target.on('testoff', toBeRemovedListener)
target.emit('testoff')
target.off('testoff', toBeRemovedListener)
target.emit('testoff')
target.offAll('message')
console.log(target)
观察者模式
class Subscribe {
constructor () {
this.observerList = []
}
addObserver (observer) {
this.observerList.push(observer)
}
notify() {
this.observerList.forEach(observer => {
observer.update()
})
}
}
class Observer {
constructor (fn) {
if (typeof fn === 'function') {
this.fn = fn
} else {
throw new Error('Observer构造器必须传入函数类型!')
}
}
update () {
this.fn()
}
}
const observerCallback = function() {
console.log('我被通知了')
}
const observer = new Observer(observerCallback)
const subscribe = new Subscribe();
subscribe.addObserver(observer);
subscribe.notify();
参考:
juejin.cn/post/684490…