Last active
June 20, 2021 12:48
-
-
Save jordan-enev/84cb4c57c2e964947ab1b67211c80a09 to your computer and use it in GitHub Desktop.
Observable
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
class Observable { | |
constructor() { | |
this._handlers = [] | |
} | |
subscribe(event, handler) { | |
this._handlers[event] = this._handlers[event] || [] | |
this._handlers[event].push(handler) | |
} | |
publish(event, eventData) { | |
const eventHandlers = this._handlers[event] | |
if (eventHandlers) { | |
for (var i = 0, l = eventHandlers.length; i < l; ++i) { | |
eventHandlers[i].call({}, eventData) | |
} | |
} | |
} | |
} |
Hi Jordan,
I'm having a hard time in understanding 7th line. Could u please help me in understanding what's the purpose of this line?
It either takes the currently created event array if it is presented in this._handlers and if not it creates a new empty event array
const handlers = []; // OUTPUT: []
handlers['event1'] = handlers['event1'] || []; // OUTPUT: [event1: []]
handlers['event2'] = handlers['event2'] || []; // OUTPUT: [event1: [], event2: []]
handlers['event1'] = handlers['event1'] || []; // OUTPUT: [event1: [], event2: []]
handlers['event1'].push('user1'); // OUTPUT: [event1: ['user1'], event2: []]
handlers['event1'] = handlers['event1'] || []; // OUTPUT: [event1: ['user1'], event2: []]
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi Jordan,
I'm having a hard time in understanding 7th line. Could u please help me in understanding what's the purpose of this line?