- 观察者模式指的是函数自动观察数据对象,一旦对象有变化,函数就会自动执行。而 js 中最常见的观察者模式就是事件触发机制
class eventObs {
constructor() {
this.handleFunc = {};
}
add(type, func) {
if (this.handleFunc[type]) {
if (this.handleFunc[type].indexOf(func) === -1) {
this.handleFunc[type].push(func);
}
} else {
this.handleFunc[type] = [func];
}
}
fire(type, func) {
try {
if (arguments.length === 1) {
let target = this.handleFunc[type];
let length = target.length;
for (let i = 0; i < length; i++) {
target[i]();
}
} else {
let target = this.handleFunc[type];
let index = target.indexOf(func);
if (index === -1) {
throw error;
}
func();
}
return true;
} catch (e) {
console.error("请触发存在的函数!");
return false;
}
}
remove(type, func) {
try {
let target = this.handleFunc[type];
let index = target.indexOf(func);
if (index === -1) {
throw error;
}
target.splice(index, 1);
} catch (e) {
console.error("请删除存在的函数!");
}
}
once(type, func) {
this.fire(type, func) ? this.remove(type, func) : null;
}
}