This repository has been archived on 2022-08-19. You can view files and clone it, but cannot push or open issues or pull requests.
hydrogen-web/src/observable/map/MappedMap.js

61 lines
1.8 KiB
JavaScript
Raw Normal View History

import BaseObservableMap from "./BaseObservableMap.js";
2019-02-21 04:18:16 +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();
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) {
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);
}
}
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) {
this.emitUpdate(key, mappedValue, newParams);
2019-02-21 04:18:16 +05:30
}
}
}
onSubscribeFirst() {
this._subscription = this._source.subscribe(this);
2019-02-21 04:18:16 +05:30
for (let [key, value] of this._source) {
const mappedValue = this._mapper(value, this._updater);
2019-02-21 04:18:16 +05:30
this._mappedValues.set(key, mappedValue);
}
super.onSubscribeFirst();
}
onUnsubscribeLast() {
this._subscription = this._subscription();
2019-02-21 04:18:16 +05:30
this._mappedValues.clear();
}
onReset() {
this._mappedValues.clear();
this.emitReset();
}
[Symbol.iterator]() {
return this._mappedValues.entries();
2019-02-21 04:18:16 +05:30
}
}