Svelte:如何订阅存储在 class 实例中
Svelte: How to subscribe to store inside a class instance
如何订阅 class 的 writable()
实例?
class User{
public money: Writable<number> = writable(0);
public goToJob(){
money.update(prev => prev + 100);
}
}
<script>
let user = new User();
</script>
<div>{user.$money}</div>
<button on:click={() => user.goToJob()}>Go to Job</button>
当我点击按钮时,我希望钱被添加并反映在 div 上。但是它不会更新,尽管我正确地引用了 money
商店。
已解决;其实很容易。只是 de-structure class 实例:
<script>
let user = new User();
let { money } = user;
</script>
<div>{$money}</div>
<button on:click={() => user.goToJob()}>Go to Job</button>
从未将商店视为 Class 属性,但商店通常用作 DTO。我对打字稿一无所知,但我认为下面的代码会让你更好地理解我在说什么:
<script>
import user from './user-store.js';
{
$user // This automatically subscribes and unsubscribe to the User store.
}
$user = {money:100};
</script>
<div>{$user.money}</div>
<button on:click={() => user.goToJob()}>
Go to Job
</button>
显示存储或为存储分配值使用 $ 前缀 ($user.money) 但调用函数不使用 (user.goToJob())
import { writable } from 'svelte/store';
const user = writable({}); // the store is an empty object by default
const userStore = {
subscribe: user.subscribe,
set: u => {
user.set(u);
console.log(u);
},
delete: () => {
user.set(null);
},
goToJob: () => {
user.update(user => {
user.money += 100;
return user;
});
}
};
export default userStore;
Link 这里:
https://svelte.dev/repl/ec4a3dee9f3c4bbebf929ee5772c48c5?version=3.46.2
最佳。
如何订阅 class 的 writable()
实例?
class User{
public money: Writable<number> = writable(0);
public goToJob(){
money.update(prev => prev + 100);
}
}
<script>
let user = new User();
</script>
<div>{user.$money}</div>
<button on:click={() => user.goToJob()}>Go to Job</button>
当我点击按钮时,我希望钱被添加并反映在 div 上。但是它不会更新,尽管我正确地引用了 money
商店。
已解决;其实很容易。只是 de-structure class 实例:
<script>
let user = new User();
let { money } = user;
</script>
<div>{$money}</div>
<button on:click={() => user.goToJob()}>Go to Job</button>
从未将商店视为 Class 属性,但商店通常用作 DTO。我对打字稿一无所知,但我认为下面的代码会让你更好地理解我在说什么:
<script>
import user from './user-store.js';
{
$user // This automatically subscribes and unsubscribe to the User store.
}
$user = {money:100};
</script>
<div>{$user.money}</div>
<button on:click={() => user.goToJob()}>
Go to Job
</button>
显示存储或为存储分配值使用 $ 前缀 ($user.money) 但调用函数不使用 (user.goToJob())
import { writable } from 'svelte/store';
const user = writable({}); // the store is an empty object by default
const userStore = {
subscribe: user.subscribe,
set: u => {
user.set(u);
console.log(u);
},
delete: () => {
user.set(null);
},
goToJob: () => {
user.update(user => {
user.money += 100;
return user;
});
}
};
export default userStore;
Link 这里:
https://svelte.dev/repl/ec4a3dee9f3c4bbebf929ee5772c48c5?version=3.46.2
最佳。