carbon/build/static/store/Subscribable.js

38 lines
915 B
JavaScript

class Subscribable {
constructor() {
this.events = {
addSelf: [],
editSelf: [],
removeSelf: [],
changeSelf: []
}
this.eventDeps = {
addSelf: ["changeSelf"],
editSelf: ["changeSelf"],
removeSelf: ["changeSelf"],
changeSelf: []
}
}
subscribe(event, callback) {
if (this.events[event]) {
this.events[event].push(callback)
} else {
throw new Error(`Cannot subscribe to non-existent event ${event}, available events are: ${Object.keys(this.events).join(", ")}`)
}
}
unsubscribe(event, callback) {
const index = this.events[event].indexOf(callback)
if (index === -1) throw new Error(`Tried to remove a nonexisting subscription from event ${event}`)
this.events[event].splice(index, 1)
}
broadcast(event, data) {
this.eventDeps[event].concat(event).forEach(eventName => {
this.events[eventName].forEach(f => f(event, data))
})
}
}
export {Subscribable}