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);
|
2019-02-26 21:13:43 +01:00
|
|
|
if (this._handlers.size === 1) {
|
2019-02-21 23:08:23 +01:00
|
|
|
this.onSubscribeFirst();
|
|
|
|
}
|
|
|
|
return () => {
|
|
|
|
if (handler) {
|
2019-07-29 10:59:07 +02:00
|
|
|
this._handlers.delete(handler);
|
2019-02-26 21:13:43 +01:00
|
|
|
if (this._handlers.size === 0) {
|
2019-02-21 23:08:23 +01:00
|
|
|
this.onUnsubscribeLast();
|
|
|
|
}
|
|
|
|
handler = null;
|
|
|
|
}
|
|
|
|
return null;
|
|
|
|
};
|
|
|
|
}
|
2019-02-26 20:48:57 +01:00
|
|
|
|
|
|
|
// Add iterator over handlers here
|
2019-02-21 23:08:23 +01:00
|
|
|
}
|
2019-07-29 10:58:27 +02:00
|
|
|
|
|
|
|
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();
|
2019-07-29 10:58:27 +02:00
|
|
|
assert.equal(c.firstSubscribeCalls, 1);
|
|
|
|
assert.equal(c.firstUnsubscribeCalls, 1);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|