1
0
mirror of https://github.com/vector-im/hydrogen-web.git synced 2025-01-14 05:57:26 +01:00
vector-im-hydrogen-web/src/observable/BaseObservableCollection.js

80 lines
1.8 KiB
JavaScript
Raw Normal View History

2019-02-21 23:08:23 +01:00
export default class BaseObservableCollection {
constructor() {
this._handlers = new Set();
}
onSubscribeFirst() {
}
onUnsubscribeLast() {
}
subscribe(handler) {
this._handlers.add(handler);
if (this._handlers.size === 1) {
2019-02-21 23:08:23 +01:00
this.onSubscribeFirst();
}
return () => {
if (handler) {
this._handlers.delete(handler);
if (this._handlers.size === 0) {
2019-02-21 23:08:23 +01:00
this.onUnsubscribeLast();
}
handler = null;
}
return null;
};
}
// Add iterator over handlers here
2019-02-21 23:08:23 +01:00
}
2020-04-09 23:19:49 +02:00
// like an EventEmitter, but doesn't have an event type
2020-04-18 19:16:16 +02:00
export class BaseObservableValue extends BaseObservableCollection {
2020-04-09 23:19:49 +02:00
emit(argument) {
for (const h of this._handlers) {
h(argument);
}
}
}
2020-04-18 19:16:16 +02:00
export class ObservableValue extends BaseObservableValue {
constructor(initialValue) {
super();
this._value = initialValue;
}
get() {
return this._value;
}
set(value) {
this._value = value;
this.emit(this._value);
}
}
export function tests() {
class Collection extends BaseObservableCollection {
constructor() {
super();
this.firstSubscribeCalls = 0;
this.firstUnsubscribeCalls = 0;
}
onSubscribeFirst() { this.firstSubscribeCalls += 1; }
onUnsubscribeLast() { this.firstUnsubscribeCalls += 1; }
}
return {
test_unsubscribe(assert) {
const c = new Collection();
2019-07-29 10:59:49 +02:00
const unsubscribe = c.subscribe({});
unsubscribe();
assert.equal(c.firstSubscribeCalls, 1);
assert.equal(c.firstUnsubscribeCalls, 1);
}
}
}