ストア
ストアとは、シンプルなストアコントラクトを介して値へのリアクティブなアクセスを可能にするオブジェクトです。 svelte/store
モジュールには、このコントラクトを満たす最小限のストア実装が含まれています。
ストアへの参照がある場合、コンポーネント内で$
文字をプレフィックスとして付けることで、その値にアクセスできます。これにより、Svelteはプレフィックス付きの変数を宣言し、コンポーネントの初期化時にストアを購読し、適切なタイミングで購読を解除します。
$
プレフィックス付きの変数への代入には、その変数が書き込み可能なストアである必要があります。代入は、ストアの.set
メソッドの呼び出しになります。
ストアは、コンポーネントの最上位レベルで宣言する必要があります(例:if
ブロックや関数内ではありません)。
(ストアの値を表さない)ローカル変数には、$
プレフィックスを付けてはなりません。
<script>
import { writable } from 'svelte/store';
const count = writable(0);
console.log($count); // logs 0
count.set(1);
console.log($count); // logs 1
$count = 2;
console.log($count); // logs 2
</script>
ストアを使用するケース
Svelte 5以前は、ストアはコンポーネント間のリアクティブな状態の作成やロジックの抽出のための主要なソリューションでした。ルーンを使用することで、これらのユースケースは大幅に減少しました。
- ロジックを抽出する場合、ルーンの普遍的なリアクティビティを利用する方が優れています。ルーンはコンポーネントの最上位レベル以外でも使用でき、JavaScriptまたはTypeScriptファイル(
.svelte.js
または.svelte.ts
ファイルの拡張子を使用)に配置することもできます。 - 共有状態を作成する場合、必要な値を含む
$state
オブジェクトを作成し、その状態を操作できます。
export const const userState: {
name: string;
}
userState = function $state<{
name: string;
}>(initial: {
name: string;
}): {
name: string;
} (+1 overload)
namespace $state
Declares reactive state.
Example:
let count = $state(0);
$state({
name: string
name: 'name',
/* ... */
});
<script>
import { userState } from './state.svelte';
</script>
<p>User name: {userState.name}</p>
<button onclick={() => {
userState.name = 'new name';
}}>
change name
</button>
複雑な非同期データストリームがある場合、または値の更新や変更のリスニングに対してより手動で制御することが重要な場合、ストアは依然として優れたソリューションです。RxJsに精通していてその知識を再利用したい場合にも、$
は便利です。
svelte/store
svelte/store
モジュールには、ストアコントラクトを満たす最小限のストア実装が含まれています。外部から更新できるストア、内部からのみ更新できるストア、およびストアを組み合わせたり派生させるためのメソッドを提供します。
writable
コンポーネントの「外部」から設定できる値を持つストアを作成する関数です。追加のset
メソッドとupdate
メソッドを持つオブジェクトとして作成されます。
set
は、設定する値を1つの引数として取るメソッドです。ストアの値が既にそれと等しくない場合、ストアの値は引数の値に設定されます。
update
は、コールバックを1つの引数として取るメソッドです。コールバックは既存のストアの値を引数として取り、ストアに設定する新しい値を返します。
import { function writable<T>(value?: T | undefined, start?: StartStopNotifier<T> | undefined): Writable<T>
Create a Writable
store that allows both updating and reading by subscription.
writable } from 'svelte/store';
const const count: Writable<number>
count = writable<number>(value?: number | undefined, start?: StartStopNotifier<number> | undefined): Writable<number>
Create a Writable
store that allows both updating and reading by subscription.
writable(0);
const count: Writable<number>
count.Readable<number>.subscribe(this: void, run: Subscriber<number>, invalidate?: () => void): Unsubscriber
Subscribe on value changes.
subscribe((value: number
value) => {
var console: Console
The console
module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
- A
Console
class with methods such as console.log()
, console.error()
and console.warn()
that can be used to write to any Node.js stream.
- A global
console
instance configured to write to process.stdout
and
process.stderr
. The global console
can be used without calling require('console')
.
Warning: The global console object’s methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the note on process I/O
for
more information.
Example using the global console
:
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console
class:
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
console.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to stdout
with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to printf(3)
(the arguments are all passed to util.format()
).
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
See util.format()
for more information.
log(value: number
value);
}); // logs '0'
const count: Writable<number>
count.Writable<number>.set(this: void, value: number): void
Set value and inform subscribers.
set(1); // logs '1'
const count: Writable<number>
count.Writable<number>.update(this: void, updater: Updater<number>): void
Update value using callback and inform subscribers.
update((n: number
n) => n: number
n + 1); // logs '2'
関数が2番目の引数として渡された場合、購読者の数が0から1に増加したときに呼び出されます(ただし、1から2などには呼び出されません)。その関数は、ストアの値を変更するset
関数と、ストアの新しい値を古い値から計算するコールバックを取るupdate
関数(ストアのupdate
メソッドのように動作します)を渡されます。購読者数が1から0に減少したときに呼び出されるstop
関数を返す必要があります。
import { function writable<T>(value?: T | undefined, start?: StartStopNotifier<T> | undefined): Writable<T>
Create a Writable
store that allows both updating and reading by subscription.
writable } from 'svelte/store';
const const count: Writable<number>
count = writable<number>(value?: number | undefined, start?: StartStopNotifier<number> | undefined): Writable<number>
Create a Writable
store that allows both updating and reading by subscription.
writable(0, () => {
var console: Console
The console
module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
- A
Console
class with methods such as console.log()
, console.error()
and console.warn()
that can be used to write to any Node.js stream.
- A global
console
instance configured to write to process.stdout
and
process.stderr
. The global console
can be used without calling require('console')
.
Warning: The global console object’s methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the note on process I/O
for
more information.
Example using the global console
:
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console
class:
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
console.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to stdout
with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to printf(3)
(the arguments are all passed to util.format()
).
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
See util.format()
for more information.
log('got a subscriber');
return () => var console: Console
The console
module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
- A
Console
class with methods such as console.log()
, console.error()
and console.warn()
that can be used to write to any Node.js stream.
- A global
console
instance configured to write to process.stdout
and
process.stderr
. The global console
can be used without calling require('console')
.
Warning: The global console object’s methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the note on process I/O
for
more information.
Example using the global console
:
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console
class:
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
console.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to stdout
with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to printf(3)
(the arguments are all passed to util.format()
).
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
See util.format()
for more information.
log('no more subscribers');
});
const count: Writable<number>
count.Writable<number>.set(this: void, value: number): void
Set value and inform subscribers.
set(1); // does nothing
const const unsubscribe: Unsubscriber
unsubscribe = const count: Writable<number>
count.Readable<number>.subscribe(this: void, run: Subscriber<number>, invalidate?: () => void): Unsubscriber
Subscribe on value changes.
subscribe((value: number
value) => {
var console: Console
The console
module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
- A
Console
class with methods such as console.log()
, console.error()
and console.warn()
that can be used to write to any Node.js stream.
- A global
console
instance configured to write to process.stdout
and
process.stderr
. The global console
can be used without calling require('console')
.
Warning: The global console object’s methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the note on process I/O
for
more information.
Example using the global console
:
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console
class:
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
console.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to stdout
with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to printf(3)
(the arguments are all passed to util.format()
).
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
See util.format()
for more information.
log(value: number
value);
}); // logs 'got a subscriber', then '1'
const unsubscribe: () => void
unsubscribe(); // logs 'no more subscribers'
writable
の値は、ページのリフレッシュなど、破棄されると失われます。ただし、値を例えばlocalStorage
に同期させる独自のロジックを作成できます。
readable
値を「外部」から設定できないストアを作成します。最初の引数はストアの初期値で、readable
への2番目の引数はwritable
への2番目の引数と同じです。
import { function readable<T>(value?: T | undefined, start?: StartStopNotifier<T> | undefined): Readable<T>
Creates a Readable
store that allows reading by subscription.
readable } from 'svelte/store';
const const time: Readable<Date>
time = readable<Date>(value?: Date | undefined, start?: StartStopNotifier<Date> | undefined): Readable<Date>
Creates a Readable
store that allows reading by subscription.
readable(new var Date: DateConstructor
new () => Date (+4 overloads)
Date(), (set: (value: Date) => void
set) => {
set: (value: Date) => void
set(new var Date: DateConstructor
new () => Date (+4 overloads)
Date());
const const interval: NodeJS.Timeout
interval = function setInterval<[]>(callback: () => void, ms?: number): NodeJS.Timeout (+2 overloads)
Schedules repeated execution of callback
every delay
milliseconds.
When delay
is larger than 2147483647
or less than 1
, the delay
will be
set to 1
. Non-integer delays are truncated to an integer.
If callback
is not a function, a TypeError
will be thrown.
This method has a custom variant for promises that is available using timersPromises.setInterval()
.
setInterval(() => {
set: (value: Date) => void
set(new var Date: DateConstructor
new () => Date (+4 overloads)
Date());
}, 1000);
return () => function clearInterval(intervalId: NodeJS.Timeout | string | number | undefined): void (+1 overload)
Cancels a Timeout
object created by setInterval()
.
clearInterval(const interval: NodeJS.Timeout
interval);
});
const const ticktock: Readable<string>
ticktock = readable<string>(value?: string | undefined, start?: StartStopNotifier<string> | undefined): Readable<string>
Creates a Readable
store that allows reading by subscription.
readable('tick', (set: (value: string) => void
set, update: (fn: Updater<string>) => void
update) => {
const const interval: NodeJS.Timeout
interval = function setInterval<[]>(callback: () => void, ms?: number): NodeJS.Timeout (+2 overloads)
Schedules repeated execution of callback
every delay
milliseconds.
When delay
is larger than 2147483647
or less than 1
, the delay
will be
set to 1
. Non-integer delays are truncated to an integer.
If callback
is not a function, a TypeError
will be thrown.
This method has a custom variant for promises that is available using timersPromises.setInterval()
.
setInterval(() => {
update: (fn: Updater<string>) => void
update((sound: string
sound) => (sound: string
sound === 'tick' ? 'tock' : 'tick'));
}, 1000);
return () => function clearInterval(intervalId: NodeJS.Timeout | string | number | undefined): void (+1 overload)
Cancels a Timeout
object created by setInterval()
.
clearInterval(const interval: NodeJS.Timeout
interval);
});
derived
1つ以上の他のストアからストアを派生させます。コールバックは、最初の購読者が購読したときに最初に実行され、ストアの依存関係が変更されるたびに実行されます。
最も単純なバージョンでは、derived
は単一のストアを取り、コールバックは派生値を返します。
import { function derived<S extends Stores, T>(stores: S, fn: (values: StoresValues<S>, set: (value: T) => void, update: (fn: Updater<T>) => void) => Unsubscriber | void, initial_value?: T | undefined): Readable<T> (+1 overload)
Derived value store by synchronizing one or more readable stores and
applying an aggregation function over its input values.
derived } from 'svelte/store';
const const doubled: Readable<number>
doubled = derived<Writable<number>, number>(stores: Writable<number>, fn: (values: number) => number, initial_value?: number | undefined): Readable<number> (+1 overload)
Derived value store by synchronizing one or more readable stores and
applying an aggregation function over its input values.
derived(const a: Writable<number>
a, ($a: number
$a) => $a: number
$a * 2);
コールバックは、2番目の引数set
とオプションの3番目の引数update
を受け入れることで、非同期的に値を設定できます。必要に応じて、どちらか一方または両方を実行します。
この場合、derived
に3番目の引数(set
またはupdate
が最初に呼び出される前の派生ストアの初期値)を渡すこともできます。初期値が指定されていない場合、ストアの初期値はundefined
になります。
import { function derived<S extends Stores, T>(stores: S, fn: (values: StoresValues<S>, set: (value: T) => void, update: (fn: Updater<T>) => void) => Unsubscriber | void, initial_value?: T | undefined): Readable<T> (+1 overload)
Derived value store by synchronizing one or more readable stores and
applying an aggregation function over its input values.
derived } from 'svelte/store';
const const delayed: Readable<number>
delayed = derived<Writable<number>, number>(stores: Writable<number>, fn: (values: number, set: (value: number) => void, update: (fn: Updater<number>) => void) => Unsubscriber | void, initial_value?: number | undefined): Readable<...> (+1 overload)
Derived value store by synchronizing one or more readable stores and
applying an aggregation function over its input values.
derived(
const a: Writable<number>
a,
($a: number
$a, set: (value: number) => void
set) => {
function setTimeout<[]>(callback: () => void, ms?: number): NodeJS.Timeout (+2 overloads)
Schedules execution of a one-time callback
after delay
milliseconds.
The callback
will likely not be invoked in precisely delay
milliseconds.
Node.js makes no guarantees about the exact timing of when callbacks will fire,
nor of their ordering. The callback will be called as close as possible to the
time specified.
When delay
is larger than 2147483647
or less than 1
, the delay
will be set to 1
. Non-integer delays are truncated to an integer.
If callback
is not a function, a TypeError
will be thrown.
This method has a custom variant for promises that is available using timersPromises.setTimeout()
.
setTimeout(() => set: (value: number) => void
set($a: number
$a), 1000);
},
2000
);
const const delayedIncrement: Readable<unknown>
delayedIncrement = derived<Writable<number>, unknown>(stores: Writable<number>, fn: (values: number, set: (value: unknown) => void, update: (fn: Updater<unknown>) => void) => Unsubscriber | void, initial_value?: unknown): Readable<...> (+1 overload)
Derived value store by synchronizing one or more readable stores and
applying an aggregation function over its input values.
derived(const a: Writable<number>
a, ($a: number
$a, set: (value: unknown) => void
set, update: (fn: Updater<unknown>) => void
update) => {
set: (value: unknown) => void
set($a: number
$a);
function setTimeout<[]>(callback: () => void, ms?: number): NodeJS.Timeout (+2 overloads)
Schedules execution of a one-time callback
after delay
milliseconds.
The callback
will likely not be invoked in precisely delay
milliseconds.
Node.js makes no guarantees about the exact timing of when callbacks will fire,
nor of their ordering. The callback will be called as close as possible to the
time specified.
When delay
is larger than 2147483647
or less than 1
, the delay
will be set to 1
. Non-integer delays are truncated to an integer.
If callback
is not a function, a TypeError
will be thrown.
This method has a custom variant for promises that is available using timersPromises.setTimeout()
.
setTimeout(() => update: (fn: Updater<unknown>) => void
update((x: unknown
x) => x + 1), 1000);
// every time $a produces a value, this produces two
// values, $a immediately and then $a + 1 a second later
});
コールバックから関数を返すと、a) コールバックが再び実行されるとき、またはb) 最後の購読者が購読を解除したときに呼び出されます。
import { function derived<S extends Stores, T>(stores: S, fn: (values: StoresValues<S>, set: (value: T) => void, update: (fn: Updater<T>) => void) => Unsubscriber | void, initial_value?: T | undefined): Readable<T> (+1 overload)
Derived value store by synchronizing one or more readable stores and
applying an aggregation function over its input values.
derived } from 'svelte/store';
const const tick: Readable<number>
tick = derived<Writable<number>, number>(stores: Writable<number>, fn: (values: number, set: (value: number) => void, update: (fn: Updater<number>) => void) => Unsubscriber | void, initial_value?: number | undefined): Readable<...> (+1 overload)
Derived value store by synchronizing one or more readable stores and
applying an aggregation function over its input values.
derived(
const frequency: Writable<number>
frequency,
($frequency: number
$frequency, set: (value: number) => void
set) => {
const const interval: NodeJS.Timeout
interval = function setInterval<[]>(callback: () => void, ms?: number): NodeJS.Timeout (+2 overloads)
Schedules repeated execution of callback
every delay
milliseconds.
When delay
is larger than 2147483647
or less than 1
, the delay
will be
set to 1
. Non-integer delays are truncated to an integer.
If callback
is not a function, a TypeError
will be thrown.
This method has a custom variant for promises that is available using timersPromises.setInterval()
.
setInterval(() => {
set: (value: number) => void
set(var Date: DateConstructor
Enables basic storage and retrieval of dates and times.
Date.DateConstructor.now(): number
Returns the number of milliseconds elapsed since midnight, January 1, 1970 Universal Coordinated Time (UTC).
now());
}, 1000 / $frequency: number
$frequency);
return () => {
function clearInterval(intervalId: NodeJS.Timeout | string | number | undefined): void (+1 overload)
Cancels a Timeout
object created by setInterval()
.
clearInterval(const interval: NodeJS.Timeout
interval);
};
},
2000
);
どちらの場合も、単一のストアの代わりに、引数の配列を最初の引数として渡すことができます。
import { function derived<S extends Stores, T>(stores: S, fn: (values: StoresValues<S>, set: (value: T) => void, update: (fn: Updater<T>) => void) => Unsubscriber | void, initial_value?: T | undefined): Readable<T> (+1 overload)
Derived value store by synchronizing one or more readable stores and
applying an aggregation function over its input values.
derived } from 'svelte/store';
const const summed: Readable<number>
summed = derived<[Writable<number>, Writable<number>], number>(stores: [Writable<number>, Writable<number>], fn: (values: [number, number]) => number, initial_value?: number | undefined): Readable<...> (+1 overload)
Derived value store by synchronizing one or more readable stores and
applying an aggregation function over its input values.
derived([const a: Writable<number>
a, const b: Writable<number>
b], ([$a: number
$a, $b: number
$b]) => $a: number
$a + $b: number
$b);
const const delayed: Readable<unknown>
delayed = derived<[Writable<number>, Writable<number>], unknown>(stores: [Writable<number>, Writable<number>], fn: (values: [number, number], set: (value: unknown) => void, update: (fn: Updater<...>) => void) => Unsubscriber | void, initial_value?: unknown): Readable<...> (+1 overload)
Derived value store by synchronizing one or more readable stores and
applying an aggregation function over its input values.
derived([const a: Writable<number>
a, const b: Writable<number>
b], ([$a: number
$a, $b: number
$b], set: (value: unknown) => void
set) => {
function setTimeout<[]>(callback: () => void, ms?: number): NodeJS.Timeout (+2 overloads)
Schedules execution of a one-time callback
after delay
milliseconds.
The callback
will likely not be invoked in precisely delay
milliseconds.
Node.js makes no guarantees about the exact timing of when callbacks will fire,
nor of their ordering. The callback will be called as close as possible to the
time specified.
When delay
is larger than 2147483647
or less than 1
, the delay
will be set to 1
. Non-integer delays are truncated to an integer.
If callback
is not a function, a TypeError
will be thrown.
This method has a custom variant for promises that is available using timersPromises.setTimeout()
.
setTimeout(() => set: (value: unknown) => void
set($a: number
$a + $b: number
$b), 1000);
});
readonly
このシンプルなヘルパー関数は、ストアを読み取り専用にします。この新しい読み取り専用ストアを使用して、元のストアからの変更を購読できます。
import { function readonly<T>(store: Readable<T>): Readable<T>
Takes a store and returns a new one derived from the old one that is readable.
readonly, function writable<T>(value?: T | undefined, start?: StartStopNotifier<T> | undefined): Writable<T>
Create a Writable
store that allows both updating and reading by subscription.
writable } from 'svelte/store';
const const writableStore: Writable<number>
writableStore = writable<number>(value?: number | undefined, start?: StartStopNotifier<number> | undefined): Writable<number>
Create a Writable
store that allows both updating and reading by subscription.
writable(1);
const const readableStore: Readable<number>
readableStore = readonly<number>(store: Readable<number>): Readable<number>
Takes a store and returns a new one derived from the old one that is readable.
readonly(const writableStore: Writable<number>
writableStore);
const readableStore: Readable<number>
readableStore.Readable<number>.subscribe(this: void, run: Subscriber<number>, invalidate?: () => void): Unsubscriber
Subscribe on value changes.
subscribe(var console: Console
The console
module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
- A
Console
class with methods such as console.log()
, console.error()
and console.warn()
that can be used to write to any Node.js stream.
- A global
console
instance configured to write to process.stdout
and
process.stderr
. The global console
can be used without calling require('console')
.
Warning: The global console object’s methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the note on process I/O
for
more information.
Example using the global console
:
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console
class:
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
console.Console.log(...data: any[]): void (+1 overload)
log);
const writableStore: Writable<number>
writableStore.Writable<number>.set(this: void, value: number): void
Set value and inform subscribers.
set(2); // console: 2
const readableStore: Readable<number>
readableStore.set(2); // ERROR
get
一般的に、ストアの値を読み取るには、ストアを購読し、時間の経過とともに変化する値を使用する必要があります。時々、購読していないストアの値を取得する必要がある場合があります。get
を使用すると、そうすることができます。
これは、購読を作成し、値を読み取り、購読を解除することによって機能します。したがって、ホットなコードパスでは推奨されません。
import { function get<T>(store: Readable<T>): T
Get the current value from a store by subscribing and immediately unsubscribing.
get } from 'svelte/store';
const const value: string
value = get<string>(store: Readable<string>): string
Get the current value from a store by subscribing and immediately unsubscribing.
get(const store: Writable<string>
store);
ストアコントラクト
store = { subscribe: (subscription: (value: any) => void) => () => undefined
subscribe: (subscription: (value: any) => void
subscription: (value: any
value: any) => void) => (() => void), set: (value: any) => undefined
set?: (value: any
value: any) => void }
svelte/store
に依存せずに、ストアコントラクトを実装することで、独自のストアを作成できます。
- ストアには、
.subscribe
メソッドが含まれている必要があります。このメソッドは、購読関数を受け入れる必要があります。この購読関数は、.subscribe
を呼び出したときに、ストアの現在の値ですぐに同期的に呼び出される必要があります。ストアの値が変更されるたびに、ストアのすべてのアクティブな購読関数は後で同期的に呼び出される必要があります。 .subscribe
メソッドは、購読解除関数を返す必要があります。購読解除関数を呼び出すと、その購読とそれに対応する購読関数はストアによって再び呼び出されなくなります。- ストアには、オプションで
.set
メソッドが含まれている場合があります。このメソッドは、ストアの新しい値を引数として受け入れる必要があり、ストアのすべてのアクティブな購読関数を同期的に呼び出します。そのようなストアは、書き込み可能なストアと呼ばれます。
RxJS Observablesとの相互運用性のために、.subscribe
メソッドは、購読解除関数を直接返すのではなく、.unsubscribe
メソッドを持つオブジェクトを返すこともできます。ただし、.subscribe
が購読を同期的に呼び出さない場合(Observable仕様では必須ではありません)、Svelteはストアの値をundefined
と認識します。