Recognize the commonEmitter

  1. NodeIn theEmitter
    const EventEmitter = require('events').EventEmitter; 
    const event = new EventEmitter(); 
    const fuc = function() {  // Listen on events
        console.log('some_event event triggered '); 
    };
    event.on('some_event', fuc); 
    setTimeout((a)= > {  event.emit('some_event');  // Trigger event}, 1000);
    event.removeListener('some_event', fuc);
Copy the code
  1. ElectronIn theEmitterAccording to theNode, we found that,EmitterIt has the following characteristics:
	export interface NodeEventEmitter {
        on(event: string | symbol, listener: Function) :this; // Register listener
        removeListener(event: string | symbol, listener: Function) :this; // Remove the listener
        emit(event: string | symbol, args: any[]): this; // Trigger the event
    }
Copy the code

In Electron, these features include ipcMain and ipcRender, which are actually an Emitter

  1. WebIn theEmitterWebIn theEmitterThere are listener methods with slightly different names:
	export interface DOMEventEmitter {
        addEventListener(event: string | symbol, listener: Function) :void; // Register listener
        removeEventListener(event: string | symbol, listener: Function) :void; // Remove the listener
        emit(event: string | symbol, args: any[]): void; // Trigger the event
    }
Copy the code

So the Emitter on the Web has documents, elements.

Next, we’ll implement an Emitter of our own