How do you write an event emitter base class that allows you to add event listeners?



How do you write an event emitter base class that allows you to add event listeners?..

Answer / Prakhar Bajpai

Here is a simple example of an EventEmitter base class in JavaScript: nnclass EventEmitter {n constructor() {n this._events = {};n }nn emit(event, ...args) {n if (!this._events[event]) return;n this._events[event].forEach(listener => listener.apply(this, args));n }nn on(event, listener) {n if (!this._events[event]) this._events[event] = [];n this._events[event].push(listener);n }nn off(event, listener) {n if (this._events[event]) {n const index = this._events[event].indexOf(listener);n if (index !== -1) this._events[event].splice(index, 1);n }n }n}n You can use it like this:nnconst myEmitter = new EventEmitter();nmyEmitter.on('sayHello', () => console.log('hello'));nmyEmitter.emit('sayHello');

Is This Answer Correct ?    0 Yes 0 No

Post New Answer

More JavaScript Interview Questions

What do you mean by script?

1 Answers  


What is camelcase in programming?

1 Answers  


Is javascript pure object oriented?

1 Answers  


How to display Alert in JavaScript

1 Answers   HCL,


What is the use of isNaN function?

1 Answers  


What is dom in javascript?

1 Answers  


How to accessing elements using javascript?

1 Answers  


What is NaN?

1 Answers  


How to reload a page using JavaScript?

1 Answers  


Does javascript support foreach loop?

1 Answers  


How to select an element by id and swapping an image?

1 Answers  


hi iM rahul.my questions is my project is a web based & developed using java,jsp. when i record it using qtp what script i will get like either browser("jdfjkf").page("nkf").... or javawindow("f d ").javaedit("Dasf").... plz clarify my doubt asap and i also need some vbscipt of java coding?

1 Answers  


Categories