发布订阅模式
粗糙版
function Event() {
this.callbacks = [];
this.result = [];
}
Event.prototype.on = function(callback) {
this.callbacks.push(callback);
};
Event.prototype.emit = function(data) {
this.result.push(data);
this.callbacks.forEach(c => {
c(this.result);
});
};
const e = new Event();
e.on((e)=>console.log(e))
e.on(()=>console.log('done'))
e.emit('haha')
e.emit('hello')
改进版
function Event() {
this.events = {};
}
Event.prototype.on = function(eventName, fn) {
if (!this.events[eventName]) {
this.events[eventName] = [];
}
this.events[eventName].push(fn);
};
Event.prototype.emit = function(eventName, data) {
if (this.events[eventName]) {
this.events[eventName].forEach(fn => fn(data));
}
};
const e = new Event();
e.on("phone", e => console.log(e));
e.on("phone", () => console.log("end"));
e.emit("phone", "喂");
e.emit("phone", "吃了吗");