有没有一种方法可以简化对web_sys内部功能的访问



在阅读了Rust这本书之后,我决定尝试一下Web Assembly。我正在创建一个简单的跟踪器脚本来练习和了解更多关于它的信息。有几个方法需要访问窗口、导航器或cookie API。每次我必须访问其中的任何一个,都会涉及到很多锅炉板代码:

pub fn start() {
let window = web_sys::window().unwrap();
let document = window.document().unwrap();
let html = document.dyn_into::<web_sys::HtmlDocument>().unwrap();
let cookie = html_document.cookie().unwrap();
}

这是不切实际的,让我很困扰。有聪明的方法解决这个问题吗?事实上,我已经尝试过使用lazy_static将所有这些都保存在global.rs文件中:

#[macro_use]
extern crate lazy_static;
use web_sys::*;
lazy_static! {
static ref WINDOW: window = {
web_sys::window().unwrap()
};
}

但编译失败,原因是:*mut u8无法在线程之间安全共享。

您可以使用?运算符而不是展开。

而不是写

pub fn start() {
let window = web_sys::window().unwrap();
let document = window.document().unwrap();
let html = document.dyn_into::<web_sys::HtmlDocument>().unwrap();
let cookie = html_document.cookie().unwrap();
}

你可以写

pub fn start() -> Result<()> {
let cookie = web_sys::window()?
.document()?
.dyn_into<web_sys::HtmlDocument>()?
.cookie()?;
Ok(())
}

这是相同数量的线路,但较少的样板,对于更简单的情况,只有一条线路。

如果你真的不想返回结果,你可以把整个东西包装在lambda中(如果你喜欢使用不稳定的特性,也可以包装在try块中(。

pub fn start() {
let cookie = (|| Result<Cookie)> {
web_sys::window()?
.document()?
.dyn_into<web_sys::HtmlDocument>()?
.cookie()
}).unwrap();
}

如果你发现你不喜欢经常重复这个-你可以使用功能

fn document() -> Result<Document> {
web_sys::window()?.document()
}
fn html() -> Result<web_sys::HtmlDocument> {
document()?.dyn_into<web_sys::HtmlDocument>()
}
fn cookie() -> Result<Cookie> {
html()?.cookie()
}
pub fn start() {
let cookie = cookie()?;
}

这是不切实际的,让我很困扰。

不确定您的问题是什么,但如果您在应用程序中一次又一次地访问同一个cookie,也许您可以将其保存在一个结构中,然后只使用该结构?在我最近的WebAssembly项目中,我保存了一些在结构中使用的元素,并通过传递来使用它们。

我还认为,也许解释你的具体用例可能会得到更具体的答案:(

最新更新