4

The below works fine and my event listener gets the custom event because it's dispatched the event from the window and my event listener is listening for loading on the window, all good.

const MyLib = mylib();
  function mylib() {
    const res = {
      init: (data) => {
        let loading = new CustomEvent('loading', {detail: { loading: true }});
        window.dispatchEvent(loading);
      }
    }
  return res;
}

event listener

 window.addEventListener('loading', handleLoading);

How can I change it to MyLib.addEventListener instead of window.addEventListener?

and..

window.dispatchEvent(loading); to MyLib.dispatchEvent(loading);

The error I get is TypeError: MyLib.addEventListener is not a function

The answer below works in a class, but id like to know if this is possible without using a class.

Bill
  • 4,614
  • 13
  • 77
  • 132
  • dispatchEvent can be called on any type of EventTarget including DOM elements other than the window. What does MyLib do? Because the window object practically means the whole browser window so it is difficult to think of another listener which has a loading event. – Máté Wiszt Dec 17 '21 at 12:16
  • when you call MyLib.init() I want it to dispatch the loading event, it will then call and API get some data and the dispatch another customer event where loading detail will be false – Bill Dec 17 '21 at 12:18
  • You don't have addEventListener function on MyLib so it is right that it throws an error. I understand that you want to use custom functions for dispatching custom events but I don't see why you cannot use the window messaging system to dispatch and listen to messages. – Máté Wiszt Dec 17 '21 at 12:47
  • There are relevant answers here: https://stackoverflow.com/a/53917410/362536 – Brad Dec 24 '21 at 06:53

2 Answers2

3

In order to dispatch and listen to events on an object, the object will need to inherit from the EventTarget interface.

class MyLib extends EventTarget {
    constructor() {
        super();
    }

    init(data) {
        let loading = new CustomEvent('loading', { detail: { loading: true } });
        this.dispatchEvent(loading);
    }
}

// somewhere myLib is an instantiation of MyLib

useEffect(() => {
    myLib.addEventListener('loading', handleLoading);
    return () => {
        myLib.removeEventListener('loading', handleLoading);
    };
}, []);
GenericUser
  • 3,003
  • 1
  • 11
  • 17
  • I should have stated that MyLib is in a `.js` file that gets loaded from a CDN, its not part of the react app that loads the event litener – Bill Dec 17 '21 at 12:55
  • is there any way od doing this without using a class? – Bill Dec 17 '21 at 13:19
  • 1
    @Bill Why would you want to? Sure, you could add the EventTarget stuff to your own object, but why go through that hassle? – Brad Dec 24 '21 at 06:53
3

Proxy can be used to achieve the requirements.

Here's a snippet that wraps the original MyLib object in a Proxy, whose get trap is activated when accessing addEventListener or dispatchEvent.

function mylib() {
  const res = {
    init: (data) => {
      let loading = new CustomEvent('loading', {detail: { loading: true }});
      MyLib.dispatchEvent(loading);
    }
  }
  return res;
}

const MyLib = new Proxy(mylib(), {
  get: function(target, prop) {
    if (prop === `addEventListener`) {
      return (...args) => window.addEventListener(...args);
    } 
    if (prop === `dispatchEvent`) {
      return (...args) => window.dispatchEvent(...args);
    }
    return target[prop];
  }
});

MyLib.addEventListener('loading', () => { console.log("Hello world !!!") });
MyLib.init();
Tyler Durden
  • 860
  • 6
  • 17