hubl/src/components/orbit-reactivity.js

54 lines
1.8 KiB
JavaScript

import {
store,
Sib,
StoreMixin
} from 'https://cdn.skypack.dev/@startinblox/core@0.17';
export const OrbitReactivity = {
name: 'orbit-reactivity',
use: [StoreMixin],
attributes: {
targetSrc: {
type: String,
default: '',
callback: function () {
this.subscribe();
}
}
},
async fetchData(value) {
this.resourceId = null;
if (this.nestedField) {
const resource = store.get(value) || await store.getData(value, this.context);
const nestedResource = await resource[this.nestedField]
this.resourceId = nestedResource ? nestedResource['@id'] : null;
} else {
this.resourceId = value;
}
this.subscribe();
},
unsubscribe(resourceId, targetSrc) {
const resourcesSub = store.subscriptionVirtualContainersIndex.get(resourceId);
const targetSub = store.subscriptionVirtualContainersIndex.get(targetSrc);
const newResourceSub = resourcesSub.filter(r => r !== targetSrc);
const newTargetSub = targetSub.filter(r => r !== resourceId);
store.subscriptionVirtualContainersIndex.set(resourceId, newResourceSub);
store.subscriptionVirtualContainersIndex.set(targetSrc, newTargetSub);
},
detached() {
this.unsubscribe(this.resourceId, this.targetSrc)
},
subscribe() {
if (this.oldResourceId && this.oldTargetSrc && (this.oldResourceId !== this.resourceId || this.oldTargetSrc !== this.targetSrc)) {
this.unsubscribe(this.oldResourceId, this.oldTargetSrc);
}
if (this.resourceId && this.targetSrc) {
store.subscribeVirtualContainerTo(this.resourceId, this.targetSrc);
store.subscribeVirtualContainerTo(this.targetSrc, this.resourceId);
this.oldResourceId = this.resourceId;
this.oldTargetSrc = this.targetSrc;
}
}
}
Sib.register(OrbitReactivity);