function callback(payload) {
console.log(`我收到事件了, 参数为 ${JSON.stringify(payload)}`);
}
class SubPub {
subscribers = [];
constructor() {
}
on(event, subscriber) {
this.subscribers[event] = this.subscribers[event] || [];
this.subscribers[event].push(subscriber);
}
off(event, subscriber) {
if (this.subscribers[event]) {
this.subscribers[event] = this.subscribers[event].filter(item => item !== subscriber);
}
}
emit(event, payload) {
if (this.subscribers[event]) {
this.subscribers[event].forEach(item => {
if (typeof item === "function") {
item(payload);
}
});
}
}
}
const pub = new SubPub();
pub.on('click', callback);
pub.on('click', callback);
pub.emit('click', { name: 'jack'} );
function test() {
console.log('run test');
}
pub.on('move', test);
pub.emit('move');
pub.off('move', test);
pub.emit('move');
pub.emit('move');
pub.emit('click');
console