Last active
December 17, 2022 21:40
-
-
Save Hacking-NASSA-with-HTML/60367e3fbeb7140a6983620cffc6a1f2 to your computer and use it in GitHub Desktop.
Javascript snippets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Summation of two variables | |
let firstName = 'John', | |
lastName = 'Doe'; | |
let greeting = `Hi ${firstName}, ${lastName}`; | |
console.log(greeting); // Hi John, Doe | |
// Observer | |
class Observer { | |
constructor() { | |
this.listeners = []; | |
} | |
addListener(name, callback) { | |
let id = {}; | |
this.listeners.push({ id, name, callback }); | |
return id; | |
} | |
addOnceListener(name, callback) { | |
let id = {}; | |
this.listeners.push({ | |
id, name, callback: () => { | |
callback(); | |
this.removeListener(id); | |
} | |
}); | |
return id; | |
} | |
removeListener(id) { this.listeners = this.listeners.filter(it => it.id != id); } | |
dispatch(name, ...args) { | |
this.listeners.filter(it => it.name == name).forEach(it => it.callback(...args)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment