- Subscribers register events with the dispatch center
- The publisher publishes events to the dispatch center
- When a publisher publishes an event, the subscription center schedules the subscriber to trigger the event.
code
// Create a subscription center class Bus {constructor() { this.obj = {} } on(key, fn) { this.obj[key] = fn; } emit(key, value) { this.obj[key].call(this, value); }}letbus = new Bus(); // Subscribe to a file whose name istest1 event bus.on('test1', (val) => {
console.log('test1'.'value:'+ val) }); // Subscribe to a file whose name istest2 events bus.on('test2'.function (val) {
console.log('test2'.'value:' + val)
});
setTimeout(() => {// Triggertest1
bus.emit('test1', 1) // triggertest2
bus.emit('test2', 2)}, 1000)Copy the code