Skip to content

Instantly share code, notes, and snippets.

@ihollander
Created November 27, 2018 18:04
Show Gist options
  • Save ihollander/e2a9a5c16fbf12179af03948ad6f65f7 to your computer and use it in GitHub Desktop.
Save ihollander/e2a9a5c16fbf12179af03948ad6f65f7 to your computer and use it in GitHub Desktop.
Observer Pattern pt1
// implementing event emitter pattern
class EventEmitter {
constructor() {
this.events = {} // initialize with empty events object
}
addEventListener(eventLabel, callback) { // create a new key for our event with the eventLabel
if (!this.events[eventLabel])
this.events[eventLabel] = []
this.events[eventLabel].push(callback)
}
dispatchEvent(eventLabel, data) {
const event = this.events[eventLabel] // lookup the event in events object
if (event) {
event.forEach(callback => { // iterate through each function assigned to the event label
callback.call(null, data) // call the function with null as the 'thisArg', and the data passed in
})
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment