Create a gist now

Instantly share code, notes, and snippets.

Embed
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

This comment has been minimized.

Show comment
Hide comment
@prochafilho

prochafilho Jan 28, 2017

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

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

@jameshoward

This comment has been minimized.

Show comment
Hide comment
@jameshoward

jameshoward May 8, 2017

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

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

@lyquocphong

This comment has been minimized.

Show comment
Hide comment
@lyquocphong

lyquocphong Mar 26, 2018

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

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

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