使用 static
來存取 JS 物件
JavaScript 模組通常會導出任意靜態物件,以供其提供的介面使用。可以透過在 extern
區塊中使用帶有 #[wasm_bindgen(thread_local_v2)]
屬性的具名 static
來從 Rust 存取這些物件。wasm-bindgen
將為這些物件繫結一個 JsThreadLocal
,它可以被複製到 JsValue
中。
這些值會被快取在執行緒本地儲存中,並且僅用於繫結靜態值或物件。對於可能會變更傳回值或拋出例外的 getter,請參閱如何導入 getter。
例如,假設有以下 JavaScript
let COLORS = {
red: 'rgb(255, 0, 0)',
green: 'rgb(0, 255, 0)',
blue: 'rgb(0, 0, 255)',
};
static
可以協助從 Rust 存取此物件
# #![allow(unused_variables)] #fn main() { #[wasm_bindgen] extern "C" { #[wasm_bindgen(thread_local_v2)] static COLORS: JsValue; } fn get_colors() -> JsValue { COLORS.with(JsValue::clone) } #}
由於 COLORS
實際上是一個 JavaScript 命名空間,因此我們可以使用相同的機制來直接參照從 JavaScript 模組導出的命名空間,甚至是導出的類別
let namespace = {
// Members of namespace...
};
class SomeType {
// Definition of SomeType...
};
export { SomeType, namespace };
此模組的繫結
# #![allow(unused_variables)] #fn main() { #[wasm_bindgen(module = "/js/some-rollup.js")] extern "C" { // Likewise with the namespace--this refers to the object directly. #[wasm_bindgen(thread_local_v2, js_name = namespace)] static NAMESPACE: JsValue; // Refer to SomeType's class #[wasm_bindgen(thread_local_v2, js_name = SomeType)] static SOME_TYPE: JsValue; // Other bindings for SomeType type SomeType; #[wasm_bindgen(constructor)] fn new() -> SomeType; } #}
可選的靜態
如果您預期嘗試存取的 JavaScript 值不一定總是可用,您可以使用 Option<T>
來處理此問題
# #![allow(unused_variables)] #fn main() { extern "C" { type Crypto; #[wasm_bindgen(thread_local_v2, js_name = crypto)] static CRYPTO: Option<Crypto>; } #}
如果 JavaScript 中未宣告或為 nullish(null
或 undefined
)crypto
,它將在 Rust 中簡單地傳回 None
。這也將適用於命名空間:只有在所有部分都被宣告且不為 nullish 時,它才會傳回 Some(T)
。
靜態字串
可以導入字串,以避免在僅需要 JsString
時通過 TextDecoder/Encoder
。這在處理 TextDecoder/Encoder
不可用的環境中(例如在音訊 worklet 中)可能很有用。
# #![allow(unused_variables)] #fn main() { #[wasm_bindgen] extern "C" { #[wasm_bindgen(thread_local_v2, static_string)] static STRING: JsString = "a string literal"; } #}