D_Inventor
11/12/2024, 8:09 AMx-for
.
In the former case, I assign the item id to a data attribute data-favourite-id="1"
.
In the latter case, I would like to inherit the item id from the parent "item" component.
What I'm running into is that my state is unintentionally shared across all components. Here is a sample of my favourites code:
typescript
alpine.data('favourites', () => ({
favouriteId: undefined,
init() {
// Favourite may be inherited from parent app (overview card for example)
if (!this.favouriteId) {
const favouriteId = this.$el.dataset['favouriteId'];
if (!favouriteId) return;
this.favouriteId = favouriteId;
}
}
}));
If I have a razor card like this:
html
<article>
<button x-data="favourites" data-favourite-id="1">Mark favourite</button>
</article>
Then the snippet works. But if I have a card like this:
html
<template x-for="article in articles">
<article x-data="overviewCard"> <!-- notice the x-date here -->
<button x-data="favourites">Mark favourite</button>
</article>
</template>
And I do this:
typescript
alpine.data('overviewCard', () => ({
init() {
this.favouriteId = this.article.id;
}
}));
Then the favouriteId is still overwritten with undefined
in the favourite component.
However, if I remove favouriteId: undefined
from the favourites component, every favourite button suddenly uses the same ID value. Does anybody know what is going on here and where I'm going wrong?D_Inventor
11/12/2024, 9:26 AMD_Inventor
11/12/2024, 9:28 AM- topLevelData
- barrrierData (includes fields set to 'undefined')
- favouriteData (sets a value for the field)