[svelte] store λ ΈνΈ
- λ₯μ§
- Development
- λΆλ₯
- Javascript
- λ±λ‘μΌ
κΈ°λ‘μ μν΄λλ μμ€μ½λ νμ€ν 리 λ€μ§κ³ ꡬκΈλ§ λ€μνκ³ λ리λμ μμ±ν΄λλ€. γ
γ
svelte storeλ λλ¨ν μ μ°νκ² μ½λλ₯Ό μμ±νκ³ μ¬μ©ν μ μλ€.
custom store
컀μ€ν
κΈ°λ₯μΌλ‘ μ€ν μ΄λ₯Ό λ§λ€ μ μλ€. μλ ꡬλ
κΈ°λ₯μ μ¬μ©ν μ μκ² νλ λΆλΆμ΄ λλ¨ν μ€μνλ€.
κ°μ λ³κ²½νλ©΄μ μ€κ°μ νΉμ κΈ°λ₯μ μ€ννλλ―ν κΈ°λ₯μ μΆκ°ν λ μ μ©ν κ²μ΄λ€. (κ°μ΄ λ³ν λλ§λ€ μ€ν λ¦¬μ§ μ
λ°μ΄νΈ νκ±°λ history κ°μ²΄ μ‘°μμ΄λ api ν΅μ .. λ±λ±)
// store.js
function createKeyword()
{
const { subscribe, set, update } = writable(window.localStorage.getItem('key-name') || '')
return {
subscribe,
set: (newValue) => {
set(newValue)
},
update: (newValue => update((oldValue) => {
if (newValue === oldValue) return oldValue
window.localStorage.setItem('key-name', newValue)
return newValue
})),
customAction: () => {
console.log('call customAction()')
},
}
}
export const keyword = createKeyword()
μ€ν μ΄λ₯Ό μ¬μ©νλλ²μ λ€μκ³Ό κ°λ€.
<!-- view.svelte -->
<p>{$keyword}</p>
<script>
import { keyword } from 'store.js'
function func()
{
$keyword = 'fooo'
keyword.customAction()
}
</script>
0κ°μ λκΈ
λ±λ‘λ λκΈμ΄ μμ΅λλ€.