Skip to content

Instantly share code, notes, and snippets.

@datchley
Last active June 7, 2021 03:40
Show Gist options
  • Save datchley/37353d6a2cb629687eb9 to your computer and use it in GitHub Desktop.
Save datchley/37353d6a2cb629687eb9 to your computer and use it in GitHub Desktop.
A straight forward EventEmitter implemented in Javascript using ES6
let isFunction = function(obj) {
return typeof obj == 'function' || false;
};
class EventEmitter {
constructor() {
this.listeners = new Map();
}
addListener(label, callback) {
this.listeners.has(label) || this.listeners.set(label, []);
this.listeners.get(label).push(callback);
}
removeListener(label, callback) {
let listeners = this.listeners.get(label),
index;
if (listeners && listeners.length) {
index = listeners.reduce((i, listener, index) => {
return (isFunction(listener) && listener === callback) ?
i = index :
i;
}, -1);
if (index > -1) {
listeners.splice(index, 1);
this.listeners.set(label, listeners);
return true;
}
}
return false;
}
emit(label, ...args) {
let listeners = this.listeners.get(label);
if (listeners && listeners.length) {
listeners.forEach((listener) => {
listener(...args);
});
return true;
}
return false;
}
}
class Observer {
constructor(id, subject) {
this.id = id;
this.subject = subject;
this.subject.addListener("change", (data) => this.onChange(data));
}
onChange(data) {
console.log(`(${this.id}) notified of change:`, data);
}
}
let observable = new EventEmitter();
let [observer1, observer2] = [
new Observer(1, observable),
new Observer(2, observable)
];
observable.emit("change", { a: 1 });
@prochafilho
Copy link

Read your article, it was succinct and to the point. Thank you dude

@jameshoward
Copy link

What license, if any, is this released under please?

@lyquocphong
Copy link

I want to ask how you can compare function inside the reduce. Can I use anonymous function with addListerner or removeListerner ?

@avivshafir
Copy link

 listeners.splice(index, 1);
//fyi, this line below is useless as the above line mutates the array in place
 this.listeners.set(label, listeners);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment