发布—订阅模式又叫观察者模式,它定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都将得到通知
不多说直接上代码,详细了解请自行百度~这里就不多说了
//发布-订阅模式
function Observer() {
let _map = new Map();
function isFunction(fn) {
if (!(fn instanceof Function)) {
throw 'arguments is not a function!'
}
}
//发布对象
this.add = function (prop) {
let [calback, obj] = [arguments[2], arguments[1]];
if (!calback) {
obj = {};
calback = arguments[1];
}
isFunction(calback);
let array = _map.get(prop) || [];
if (_map.has(prop)) {
array.push({
obj,
calback,
})
} else {
array.push({
obj,
calback,
})
_map.set(prop, array);
}
}
//订阅对象
this.subscribe = function (props, ...args) {
let result = _map.get(props) || [];
result.forEach((val) => {
val.calback.apply(val.obj, args);
})
}
//移除订阅对象
this.remove = function (props) {
let target = arguments[1];
if (props) {
if (target) {
let result = _map.get("props");
result.forEach((val, index) => {
if (Object.is(target, val.obj)) {
result.splice(index, 1)
}
})
} else {
_map.delete('props');
}
} else {
_map.clear()
}
}
}
let obs = new Observer();
obs.add("emit", (a, b) => {
console.log(this) //打印window
console.log(a, b) //打印1,2
})
obs.add("emit", { a: 1 }, function () {
console.log(this) //打印{a:1}
console.log(arguments) //打印window
})
obs.subscribe('emit', 1, 2, 3)