Skip to content

Instantly share code, notes, and snippets.

@hoangtrucit
Created April 21, 2020 02:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hoangtrucit/8f6412a489a9619b2006bc9589ca7be8 to your computer and use it in GitHub Desktop.
Save hoangtrucit/8f6412a489a9619b2006bc9589ca7be8 to your computer and use it in GitHub Desktop.
class Event {
name = null;
callbacks = [];
constructor(name) {
this.name = name;
}
registerCallback = (callback) => {
this.callbacks.push(callback);
};
}
class EventNotification {
events = {};
addEventListener = (eventName, callback) => {
if (!this.events[eventName]) {
this.events[eventName] = new Event(eventName);
}
this.events[eventName].registerCallback(callback);
};
dispatchEvent = (eventName, eventArgs) => {
if (!this.events[eventName]) {
return console.log("no event name: ", eventName);
}
console.log("dispatch event ", eventName);
this.events[eventName].callbacks.forEach((callback) => callback(eventArgs));
};
removeAllEventListeners = () => {
for (let item in this.events) {
delete this.events[item];
}
};
removeEventListener = (eventName, callback) => {
if (!this.events[eventName]) return;
const len = this.events[eventName].callbacks.length;
for (let i = 0; i < len; i++) {
if (this.events[eventName].callbacks[i] === callback) {
this.events[eventName].callbacks.splice(i, 1);
}
}
};
}
const eventNotification = new EventNotification();
const cb1 = () => console.log("update 1");
const cb2 = () => console.log("update 2");
eventNotification.addEventListener("updateTask", cb1);
eventNotification.addEventListener("updateTask", cb2);
// eventNotification.removeEventListener("updateTask", cb1);
// eventNotification.removeEventListener("updateTask", cb2);
// eventNotification.removeAllEventListeners();
// console.log(eventNotification.events);
setTimeout(() => {
console.log("run");
eventNotification.dispatchEvent("updateTask");
eventNotification.removeEventListener("updateTask", cb1);
eventNotification.removeEventListener("updateTask", cb2);
eventNotification.dispatchEvent("updateTask");
// eventNotification.removeAllEventListeners();
// console.log(eventNotification.events);
}, 2000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment