Skip to content

Instantly share code, notes, and snippets.

@jordan-enev
Last active June 20, 2021 12:48
Show Gist options
  • Save jordan-enev/84cb4c57c2e964947ab1b67211c80a09 to your computer and use it in GitHub Desktop.
Save jordan-enev/84cb4c57c2e964947ab1b67211c80a09 to your computer and use it in GitHub Desktop.
Observable
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)
}
}
}
}
@abhinavkushagra
Copy link

abhinavkushagra commented Jun 20, 2021

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?

@Bare7a
Copy link

Bare7a commented Jun 20, 2021

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