Carbon/build/static/store/Subscribable.js

39 lines
915 B
JavaScript
Raw Normal View History

2020-10-15 03:43:37 +00:00
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) {
2020-10-15 13:24:15 +00:00
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)
2020-10-15 03:43:37 +00:00
}
broadcast(event, data) {
this.eventDeps[event].concat(event).forEach(eventName => {
this.events[eventName].forEach(f => f(event, data))
})
}
}
export {Subscribable}