观察者模式 / 发布订阅模式
- 需要3阶段 框架语法中的双向数据绑定配合执行
- 主体状态改变 相关个体执行对应的函数程序
二阶段的主要程序内容
通过构造函数创建实例化对象
1. 属性 - 对象存储 要执行函数程序的 类型 和 具体的函数程序
事件类型 和 事件处理函数
2. 函数方法
- add() 添加方法
向对象中 添加 事件类型 和 事件处理函数
判断 事件类型是否存在
如果事件类型不存在 证明 本次事件是第一次添加 - 直接添加事件类型 和 事件处理函数
如果事件类型存在 判断事件处理函数是否存在 - 不存在 添加事件处理函数
- delete() 删除方法
从对象中 删除 指定事件类型 对应的 事件处理函数
判断事件类型是否存在
如果不存在 - 不操作
如果存在 - 循环遍历删除事件 存在于this.msg中 再执行删除操作
- ext() 执行方法
执行 指定事件类型中 添加的事件处理函数
判断事件类型是否存在
如果不存在 - 不操作
如果存在 - 循环遍历 判断执行事件是存在this.msg中 存在 - 执行操作
- clear() 清除方法
清除 所有 事件类型和事件处理函数
直接给消息盒子 赋值空对象
this.msg={}
观察者模式基本语法
//观察者模式 基本框架语法
class Observer {
constructor() {
// 一个对象 存储 事件类型 事件处理函数
// 一般称为 消息盒子
// 对象的键名:事件类型 对象的键值:事件处理函数 (数组形式存储)
this.msg = {}
}
// 新增方法
add() {}
// 删除方法
delete() {}
// 执行方法
ext() {}
// 清除方法
clear() {}
}
举个例子:
class Observer {
constructor() {
this.msg = {}
}
// 新增方法
add(type, ...funArr) {
if (this.msg[type] === undefined) {
// 证明 this.msg 中 没有 当前事件类型 可以 直接添加
this.msg[type] = funArr
} else {
// 证明 this.msg 中 有 当前 事件类型
// 判断 事件处理函数 不存在 就添加
funArr.forEach(item => {
if (this.msg[type].indexOf(item) === -1) {
this.msg[type].push(item)
}
})
}
}
// 删除方法
delete(type, ...funArr) {
if (this.msg[type] !== undefined) {
// 有事件类型
funArr.forEach(item => {
// 找到相对应的删除事件
if (this.msg[type].indexOf(item) !== -1) {
this.msg[type].splice(this.msg[type].indexOf(item), 1)
}
})
}
}
// 执行方法
ext(type, ...funArr) {
if (this.msg[type] !== undefined) {
funArr.forEach(item => {
if (this.msg[type].indexOf(item) !== -1) {
item()
}
})
}
}
// 清除方法
clear() {
// 给消息盒子赋值空对象 完全清空
this.msg = {}
}
}
// 通过构造函数创建实例化对象
const observerObj = new Observer()
console.log(observerObj);
// add方法添加事件类型处理函数
observerObj.add('article', article1, article4)
observerObj.add('article', article1, article2, article3)
observerObj.add('lottery', lottery1, lottery2, lottery3, lottery4)
observerObj.add('a')
// delete方法删除事件类型处理函数
observerObj.delete('article', article2, article4)
// ext方法执行事件类型处理函数
observerObj.ext('test', test1, test2, test3, test4)
observerObj.ext('article', article1, article2, article3, article4)
observerObj.ext('lottery', lottery1, lottery2, lottery3, lottery4)
// 清除方法清除事件类型处理函数
observerObj.clear()
// 提前定义好的要执行的事件处理函数
// 推送文章类
function article1() {console.log('文章1')};
function article2() {console.log('文章2')};
function article3() {console.log('文章3')};
function article4() {console.log('文章4')};
// 抽奖类
function lottery1() {console.log('抽奖活动1')};
function lottery2() {console.log('抽奖活动2')};
function lottery3() {console.log('抽奖活动3')};
function lottery4() {console.log('抽奖活动4')};
// 游戏类
function game1() {console.log('游戏活动1')};
function game2() {console.log('游戏活动2')};
function game3() {console.log('游戏活动3')};
function game4() {console.log('游戏活动4')};
function game5() {console.log('游戏活动5')};
// 心里测试
function test1() {console.log('心里测试1')};
function test2() {console.log('心里测试2')};
function test3() {console.log('心里测试3')};
function test4() {console.log('心里测试4')};