观察者模式的含义,是一个观察者在观察某件事件的进展,当进行到一定程度的时候就会执行某个操作。
例如:我要做核酸,但是做核酸的人比较多,我就不停的观察,当排队的人少的时候,我就去做。
class Watcher{
// 定义存储观察的事情和函数的容器
container = {}
// 需要有添加观察事情的方法
bind(type, handler) { // type为观察的事情;handler为要执行的函数
// 需要将观察的事情和要执行的函数存下来,以便后面拿出来执行
if(!this.container[type]) { // 判断是否观察过
this.container[type] = [] // 没有观察过,就给对应的值赋值为空数组
}
// 给数组添加要执行的函数
this.container[type].push(handler)
}
// 触发事情的进展
touch(type) { // type为事情的类型
if(!this.container[type]) { // 判断是否观察过
return
}
// 遍历观察的事情对应的所有函数并调用
this.container[type].forEach(item => {
item()
})
}
// 这件事情结束后要取消观察的事情对应的某个函数
unbind(type, handler) {
if(!this.container[type]) { // 判断是否观察过
return
}
// 找到这个函数在数组中的下标
var index = this.container[type].findIndex(item => item === handler)
// 从数组中删除这个函数
index >= 0 && this.container[type].splice(index, 1)
// 如果删除后数组为空,就将这个观察的事情取消
if(!this.container[type].length) {
delete this.container[type]
}
}
// 取消观察
clear(type) {
delete this.container[type] // 删除键值对
}
}
使用示例:
// 创建观察者
var w = new Wathcer()
// 观察事件a1, 执行fa1函数
w.bind('a1', fa1)
function fa1() {
consolel.log('时机到了,该执行了1')
}
// 观察事件a1添加要执行fa2函数
w.bind('a1', fa2)
function fa2() {
consolel.log('时机到了,该执行了2')
}
// 触发a1事件
w.touch('a1')
// 取消执行函数fa1
w.unbind('a1', fa1)
// 触发a1事件
w.touch('a1')
// 取消观察a1事件
w.clear()
// 触发a1事件
w.touch('a1')