We are working on creating custom event listener on Javascript. Tried out a few examples but couldn't get custom event listener to be called. Code example:
events.js
function init() {
return new Promise(() => {
console.log('successfully initialized!');
});
}
// this symbolizes some event occurring randomly. in reality, this will eventually be
// something like a webhook getting hit, or a websocket, etc. for now we just use
// setTimeout to simulate this event coming in at some time after init has been called
setTimeout(on, 15000);
// on is called anytime any event occurs. in this example, we hardcode that event1 occurred
function on() {
console.log('event1 occurred in events.js');
return 'event1';
}
const events = {
init,
on,
};
export default events;
index.js
events.init(() => {
// here we should see console log about successful initialization
}).then(() => {
// here, we want to "listen" for event1 to occur
events.on('event1', () => {
console.log('we were notified about event1 happening!');
});
});
In this example we see following being displayed in browser console
successfully initialized!
And then few seconds later:
event1 occurred in events.js
As shown in example callback code for "event1" from index.js is never called, instead "on" function from events.js is called. What we need is a custom event listener to work so we can call "event1" from index.js console.log should display
we were notified about event1 happening!
Thank you for reviewing the question and helping with solution.