2019-02-27 01:18:57 +05:30
|
|
|
import BaseObservableMap from "./BaseObservableMap.js";
|
2019-02-21 04:18:16 +05:30
|
|
|
|
2019-02-27 01:18:57 +05:30
|
|
|
export default class MappedMap extends BaseObservableMap {
|
|
|
|
constructor(source, mapper) {
|
|
|
|
super();
|
|
|
|
this._source = source;
|
2019-02-21 04:18:16 +05:30
|
|
|
this._mapper = mapper;
|
|
|
|
this._mappedValues = new Map();
|
2019-02-27 01:18:57 +05:30
|
|
|
this._updater = (key, params) => { // this should really be (value, params) but can't make that work for now
|
|
|
|
const value = this._mappedValues.get(key);
|
|
|
|
this.onUpdate(key, value, params);
|
|
|
|
};
|
2019-02-21 04:18:16 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
onAdd(key, value) {
|
2019-02-27 01:18:57 +05:30
|
|
|
const mappedValue = this._mapper(value, this._updater);
|
2019-02-21 04:18:16 +05:30
|
|
|
this._mappedValues.set(key, mappedValue);
|
|
|
|
this.emitAdd(key, mappedValue);
|
|
|
|
}
|
|
|
|
|
|
|
|
onRemove(key, _value) {
|
|
|
|
const mappedValue = this._mappedValues.get(key);
|
|
|
|
if (this._mappedValues.delete(key)) {
|
|
|
|
this.emitRemove(key, mappedValue);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-02-27 01:18:57 +05:30
|
|
|
onUpdate(key, value, params) {
|
2019-02-21 04:18:16 +05:30
|
|
|
const mappedValue = this._mappedValues.get(key);
|
|
|
|
if (mappedValue !== undefined) {
|
|
|
|
const newParams = this._updater(value, params);
|
|
|
|
if (newParams !== undefined) {
|
2019-02-27 01:18:57 +05:30
|
|
|
this.emitUpdate(key, mappedValue, newParams);
|
2019-02-21 04:18:16 +05:30
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
onSubscribeFirst() {
|
2019-02-27 01:18:57 +05:30
|
|
|
this._subscription = this._source.subscribe(this);
|
2019-02-21 04:18:16 +05:30
|
|
|
for (let [key, value] of this._source) {
|
2019-02-27 01:18:57 +05:30
|
|
|
const mappedValue = this._mapper(value, this._updater);
|
2019-02-21 04:18:16 +05:30
|
|
|
this._mappedValues.set(key, mappedValue);
|
|
|
|
}
|
|
|
|
super.onSubscribeFirst();
|
|
|
|
}
|
|
|
|
|
|
|
|
onUnsubscribeLast() {
|
2019-02-27 01:18:57 +05:30
|
|
|
this._subscription = this._subscription();
|
2019-02-21 04:18:16 +05:30
|
|
|
this._mappedValues.clear();
|
|
|
|
}
|
|
|
|
|
|
|
|
onReset() {
|
|
|
|
this._mappedValues.clear();
|
|
|
|
this.emitReset();
|
|
|
|
}
|
|
|
|
|
|
|
|
[Symbol.iterator]() {
|
2019-02-28 03:20:08 +05:30
|
|
|
return this._mappedValues.entries();
|
2019-02-21 04:18:16 +05:30
|
|
|
}
|
|
|
|
}
|