https://bigfrontend.dev/zh/problem/create-an-Event-Emitter
    [zhika]

    1. class EventEmitter {
    2. constructor() {
    3. this.subs = {};
    4. }
    5. subscribe(eventName, callback) {
    6. this.subs[eventName] ??= new Map();
    7. const key = Symbol();
    8. this.subs[eventName].set(key, callback);
    9. return {
    10. release: () => {
    11. this.subs[eventName].delete(key);
    12. }
    13. }
    14. }
    15. emit(eventName, ...args) {
    16. console.log(this.subs[eventName]);
    17. for(const callback of this.subs[eventName].values()) {
    18. try {
    19. callback.apply(this,...args);
    20. } catch (e) {
    21. // Make sure to catch any errors - I was asked this in interview
    22. }
    23. }
    24. }
    25. }
    26. const emitter = new EventEmitter()
    27. function callback1(...args){console.log(this,'111',args)}
    28. function callback2(...args){console.log(this,'222',args)}
    29. const sub1 = emitter.subscribe('event1', callback1)
    30. const sub2 = emitter.subscribe('event2', callback2)
    31. const sub3 = emitter.subscribe('event1', callback2)
    32. sub1.release()
    33. // sub3.release()
    34. console.log(emitter.emit('event1', 1, 2));