绑定到对象集合
Binding to a collections of objects
我有一个对象映射,需要将它们的某些字段绑定到标签。当然,我可以将地图转换为数组并使用#each,但在这种情况下,对单个地图条目的更新将更新对所有标签的绑定。我想要原子更新,即将输入绑定到单独的对象,同时使用 #each 构建整个东西(手动映射 50 个左右的项目并不好玩)。有什么办法可以实现吗?
解决方案(有点hacky)如下:
App.svelte:
<script>
import Update from "./Update.js"
let items = [
{ id: 1, value: 'a' },
{ id: 2, value: 'b' },
{ id: 3, value: 'c' },
{ id: 4, value: 'd' },
{ id: 5, value: 'e' }
];
</script>
<style>
:global(.myclass) {
animation: pulse 2s ease-out
}
@keyframes pulse {
0%, 75% {
background-color: red;
}
100% {
background-color: white;
}
}
</style>
{#each items as item (item.id)}
<input type="text" bind:value={item.value} use:Update={item.value}>
{/each}
Update.js 操作:
export default function update(node, foo) {
let faa = foo
return {
update(foo) {
if (foo === faa) return
faa = foo
// rest of code will only be executed if the value really changed
node.style.animation = 'none';
node.offsetHeight; /* trigger reflow */
node.style.animation = null;
node.classList.add("myclass");
}
}
}
我有一个对象映射,需要将它们的某些字段绑定到标签。当然,我可以将地图转换为数组并使用#each,但在这种情况下,对单个地图条目的更新将更新对所有标签的绑定。我想要原子更新,即将输入绑定到单独的对象,同时使用 #each 构建整个东西(手动映射 50 个左右的项目并不好玩)。有什么办法可以实现吗?
解决方案(有点hacky)如下:
App.svelte:
<script>
import Update from "./Update.js"
let items = [
{ id: 1, value: 'a' },
{ id: 2, value: 'b' },
{ id: 3, value: 'c' },
{ id: 4, value: 'd' },
{ id: 5, value: 'e' }
];
</script>
<style>
:global(.myclass) {
animation: pulse 2s ease-out
}
@keyframes pulse {
0%, 75% {
background-color: red;
}
100% {
background-color: white;
}
}
</style>
{#each items as item (item.id)}
<input type="text" bind:value={item.value} use:Update={item.value}>
{/each}
Update.js 操作:
export default function update(node, foo) {
let faa = foo
return {
update(foo) {
if (foo === faa) return
faa = foo
// rest of code will only be executed if the value really changed
node.style.animation = 'none';
node.offsetHeight; /* trigger reflow */
node.style.animation = null;
node.classList.add("myclass");
}
}
}