含义:
on方法来订阅一个事件,当这个事件被发布时,所有订阅这个事件的回调函数将被调用。
emit方法用于发布一个事件。
off方法来取消订阅一个事件。
once方法代表当前时间只执行一次。(订阅者只订阅事件,之后就取消订阅)
on、emit、off
interface EventFace {
on: (event: string, callback: Function) => void,
emit: (event: string, ...args: Array<any>) => void,
off: (event: string, callback: Function) => void
}
class Dispatch implements EventFace {
list: any
constructor() {
this.list = {}
}
on = (event: string, callback: Function) => {
if (!this.list[event]) {
this.list[event] = []
}
this.list[event].push(callback)
};
emit = (event: string, ...args: Array<any>) => {
if (!this.list[event]) {
console.error('事件未注册');
return;
}
this.list[event].forEach((callback: Function) => {
callback.apply(this, args)
});
};
off = (event: string, callback: Function) => {
if (this.list[event] && callback) {
this.list[event] = this.list[event].filter((item: Function) => item != callback)
}
else {
console.error('事件未注册');
}
}
}
let d = new Dispatch();
// 发布订阅示例
d.on('event1', (...data: Array<any>) => {
console.log(`Received event1: ${data}`);
});
d.on('event2', (...data: Array<any>) => {
console.log(`Received event2: ${data}`);
});
d.emit('event1', 1, 'Hello from event1', true);
d.emit('event2', 2, 'Hello from event2', true);
// 取消订阅示例
function onMessageReceived(data) {
console.log(`Received message: ${data}`);
}
// 订阅事件
d.on('message', onMessageReceived);
// 发布事件,订阅者会收到通知
d.emit('message', 'Hello, world!');
// 取消订阅,使订阅者不再接收事件通知
d.off('message', onMessageReceived);
// 再次发布事件,取消订阅的订阅者不会收到通知
d.emit('message', 'Hello again!')
当发布消息以后,订阅者能收到消息。
当订阅者取消订阅以后,订阅者不能收到消息。
once
interface EventFace {
on: (event: string, callback: Function) => void,
emit: (event: string, ...args: Array<any>) => void,
off: (event: string, callback: Function) => void,
once: (event: string, callback: Function) => void,
}
class Dispatch implements EventFace {
list: any
constructor() {
this.list = {}
}
on = (event: string, callback: Function) => {
if (!this.list[event]) {
this.list[event] = []
}
this.list[event].push(callback)
};
emit = (event: string, ...args: Array<any>) => {
if (!this.list[event]) {
console.error('事件未注册');
return;
}
this.list[event].forEach((callback: Function) => {
callback.apply(this, args)
});
};
off = (event: string, callback: Function) => {
if (this.list[event] && callback) {
this.list[event] = this.list[event].filter((item: Function) => item != callback)
}
else {
console.error('事件未注册');
}
}
once = (event: string, callback: Function) => {
const onceCallback = (...args: Array<any>) => {
callback(args)
this.off(event, onceCallback)
}
this.on(event, onceCallback);
};
}
let d = new Dispatch();
// 订阅一个只调用一次的事件
d.once('message', (data: Array<any>) => {
console.log(`Received message (once): ${data}`);
});
// 发布事件
d.emit('message', 'Hello, world!');
// 再次发布事件
d.emit('message', 'Hello again!');
只输出了一次,因为只执行一次订阅,之后取消订阅了,所以第二次发布事件不会触发事件的回调