My object is like:
const inventory = {
maxSlots: 24,
content: [
{id: "item_01", quantity: 5, slotId: 0},
{id: "item_02", quantity: 2, slotId: 2},
{id: "item_03", quantity: 1, slotId: 6},
]
};
I need custom methods like:
inventory.getRemainingSlots()inventory.getFirstFreeSlotid()inventory.addItem()(this one depends oninventory.getFirstFreeSlotid())
How should I make this object reactive?
- Single writable?
- Custom store with
get,set,updateandsubscribemethods? - Class instance with writable?
- One writable for each single property, then a store of stores?
I've reached this point so far:
inventoryStore.js
function createStore() {
const { subscribe, set, update } = writable({
maxSlots: 8,
content: [
{ id: "item_01", quantity: 5, slotId: 0 },
{ id: "item_02", quantity: 2, slotId: 2 },
{ id: "item_03", quantity: 1, slotId: 6 },
],
});
return {
// Store methods
subscribe,
set,
update,
get: () => get({ subscribe }),
// Custom methods
getContent: () => {
// I can't use this in .svelte files
return inventoryStore.get().content;
},
getFirstFreeSlotId: () => {
const content = inventoryStore.get().content;
const maxSlots = inventoryStore.get().inventoryMaxSlots;
for (let _slotId = 0; _slotId < maxSlots; _slotId++) {
const foundItem = content.find(_x => _x.slotId === _slotId);
if (!foundItem?.id) {
return _slotId;
}
}
return -1;
}
};
}
export const inventoryStore = createStore();
I figured it out:
/stores/inventoryStore+page.svelte