发布订阅模式定义了一种一对多的关系,让多个订阅者对象同时监听某一个主题对象,当主题对象发生变化时,它会通知所有订阅者对象,使它们能够自动更新。
const Event = function () {
// 订阅者依赖集
const listeners = {};
function subscribe(key, fn) {
if (!listeners[key]) {
listeners[key] = [];
}
listeners[key].push(fn);
}
function publish() {
const key = Array.prototype.shift.call(arguments);
const fns = listeners[key];
if (!fns || !fns.length) {
return;
}
for (let i = 0, fn; fn = fns[i++];) {
fn.apply(this, arguments);
}
}
function unsubscribe(key, fn) {
const fns = listeners[key];
if (!fns || !fns.length) {
return;
}
if (!fn) {
listeners[key] = [];
return;
}
for (let i = fns.length - 1; i >= 0; i--) {
if (fns[i] === fn) {
fns.splice(i, 1);
}
}
}
function once(key, fn) {
if (!listeners[key]) {
listeners[key] = [];
}
const _once = (...args) => {
fn.apply(this, args);
this.unsubscribe(key, _once);
};
listeners[key].push(_once);
}
return {
subscribe,
publish,
unsubscribe,
once,
}
};
总结
发布—订阅模式,可以为时间上的解耦,也可以为对象之间的解耦。它的应用非常广泛,既可以用在异步编程中,也可以帮助我们完成更松耦合的代码编写。