Created
November 27, 2018 18:04
-
-
Save ihollander/e2a9a5c16fbf12179af03948ad6f65f7 to your computer and use it in GitHub Desktop.
Observer Pattern pt1
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
// 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