pub struct Readable<T> { /* private fields */ }
Expand description
Rust-managed Readable
Svelte store.
Implementations§
Source§impl<T: 'static> Readable<T>
impl<T: 'static> Readable<T>
Sourcepub fn new(initial_value: T) -> Self
pub fn new(initial_value: T) -> Self
Creates a Readable
Svelte store.
This function is only implemented for types that can be converted
into JsValue
. This includes all types annotated with
#[wasm_bindgen]
. If your type does not provide an Into<JsValue>
implementation, use Readable::new_mapped
instead.
§Examples
Using a type that already provides an implementation of
Into<JsValue>
.
use svelte_store::Readable;
let store = Readable::new(0u8);
Using a type annotated with #[wasm_bindgen]
.
use svelte_store::Readable;
use wasm_bindgen::prelude::*;
#[derive(Clone)]
#[wasm_bindgen]
pub struct MyStruct;
let store = Readable::new(MyStruct);
Sourcepub fn new_mapped<F>(initial_value: T, mapping_fn: F) -> Self
pub fn new_mapped<F>(initial_value: T, mapping_fn: F) -> Self
Creates a new Readable
Svelte store which calls its mapping fn each
time the store is set, to produce a JsValue
.
This method should be used whenever Readable::new
cannot be,
due to lacking trait compatibility.
§Examples
Creating a store of Vec<u8>
.
use svelte_store::Readable;
use wasm_bindgen::prelude::*;
let values = vec![7u8; 7];
let store = Readable::new_mapped(values, |values: &Vec<u8>| {
values
.iter()
.cloned()
.map(JsValue::from)
.collect::<js_sys::Array>()
.into()
});
Sourcepub fn set(&mut self, new_value: T)
pub fn set(&mut self, new_value: T)
Sets the value of the store, notifying all store listeners the value has changed.
Sourcepub fn set_with<F, O>(&mut self, f: F) -> O
pub fn set_with<F, O>(&mut self, f: F) -> O
Calls the provided f
with a &mut T
, returning
whatever f
returns. After this function is called,
the store will be updated and all store listeners will
be notified.
Sourcepub fn get_store(&self) -> JsValue
pub fn get_store(&self) -> JsValue
Gets the store that can be directly passed to JS and subscribed to.
§Examples
use wasm_bindgen::prelude::*;
use svelte_store::Readable;
#[wasm_bindgen(typescript_custom_section)]
const TYPESCRIPT_TYPES: &str = r#"
import type { Readable } from "svelte/store";
type ReadableNumber = Readable<number>;
"#;
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(typescript_type = "ReadableNumber")]
type ReadableNumber;
}
#[wasm_bindgen]
pub struct MyStruct {
my_number: Readable<u8>,
}
#[wasm_bindgen]
impl MyStruct {
#[wasm_bindgen(getter)]
pub fn number(&self) -> ReadableNumber {
self.my_number.get_store().into()
}
}