open-consul/ui-v2/app/utils/dom/event-source/storage.js
John Cowen 74dbc71c84 ui: Change vocab of ReopenableEventSource from 'reopen' to 'open' (#5973)
You can potentially close an EventSource before its first tick by
immediately setting the readyState to a non-open state. Therefore it
never opens.

Calling `open` will then open it.

'Open' fits better than 'reopen' when taking the above into account
2019-09-04 08:35:02 +00:00

41 lines
1.1 KiB
JavaScript

export default function(EventTarget, P = Promise) {
const handler = function(e) {
if (e.key === this.configuration.key) {
P.resolve(this.getCurrentEvent()).then(event => {
this.configuration.cursor++;
this.dispatchEvent(event);
});
}
};
return class extends EventTarget {
constructor(cb, configuration) {
super(...arguments);
this.source = cb;
this.handler = handler.bind(this);
this.configuration = configuration;
this.configuration.cursor = 1;
this.dispatcher = configuration.dispatcher;
this.open();
}
dispatchEvent() {
if (this.readyState === 1) {
return super.dispatchEvent(...arguments);
}
}
close() {
this.dispatcher.removeEventListener('storage', this.handler);
this.readyState = 2;
}
reopen() {
this.dispatcher.addEventListener('storage', this.handler);
this.readyState = 1;
}
getCurrentEvent() {
return {
type: 'message',
data: this.source(this.configuration),
};
}
};
}