前言
- 发布-订阅是一种消息范式,通过定义发布者、订阅者、调度中心来完成消息通信。这是前端常用的消息通讯模式。
- 事件由调度中心统一管理,由订阅者在调度中心订阅(注册)事件,发布者通过调度中心发布(触发)事件,订阅者通过事件收到消息,以达到消息通信。
实现
function EventCenter() {
this.events = {};
}
EventCenter.prototype.on = function (eventName, callback) {
if (!this.events[eventName]) {
this.events[eventName] = [callback];
} else {
this.events[eventName].push(callback);
}
};
EventCenter.prototype.trigger = function (eventName) {
if (this.events[eventName]) {
this.events[eventName].forEach((cb) => cb());
}
};
EventCenter.prototype.off = function (eventName, callback) {
if (this.events[eventName]) {
const index = this.events[eventName].findIndex(
(cb) => cb === callback
);
if (index !== -1) {
this.events[eventName].splice(index, 1);
}
if (this.events[eventName].length === 0 || !callback) {
delete this.events[eventName];
}
}
};
EventCenter.prototype.once = function (eventName, callback) {
const that = this;
const fn = function () {
callback();
that.off(eventName, fn);
};
this.on(eventName, fn);
};
const event = new EventCenter();
const run = function () {
console.log("running: 订阅发布成功");
};
const jump = function () {
console.log("jumping: 订阅发布成功");
};
const fly = function () {
console.log("flying: 订阅发布成功");
};
event.on("running", run);
event.on("jumping", jump);
event.once("flying", fly);
event.off("jumping", jump);
event.trigger("jumping");
event.trigger("running");
event.trigger("running");
event.trigger("flying");
event.trigger("flying");
运行结果