zoukankan      html  css  js  c++  java
  • [WASM Rust] Use the js-sys Crate to Invoke Global APIs Available in Any JavaScript Environment

    js-sys offers bindings to all the global APIs available in every JavaScript environment as defined by the ECMAScript standard.

    In this lesson, we will install and use js-sys to invoke JavaScript's Date API to grab the current time. The date will need to be converted to a value Rust can use and display that date from Rust in the browser.

    Cargo.toml:

    [dependencies]
    cfg-if = "0.1.5"
    wasm-bindgen = "0.2.25"
    js-sys = "0.2"

    lib.rs:

    // Called by our JS entry point to run the example
    #[wasm_bindgen]
    pub fn run() {
        let now = js_sys::Date::now();
        let now_date = js_sys::Date::new(&JsValue::from_f64(now));
        
        let val = document.createElement("p");
    
        val.set_inner_html(&format!(
            "Hello from Rust, it's {}:{}",
            now_date.get_hours(),
            now_date.get_minutes()
        ));
        document.body().append_child(val);
    }

    index.js:

    import("../crate/pkg").then(module => {
        module.run();
      });
  • 相关阅读:
    js入门之DOM
    js入门之字符串常用的方法
    js入门之内置数组对象 Array
    js入门之内置对象Date
    js入门之内置对象Math
    js入门之对象
    js入门之函数
    js入门之数组
    js入门第二篇之流程控制语句
    js入门第一篇
  • 原文地址:https://www.cnblogs.com/Answer1215/p/9920062.html
Copyright © 2011-2022 走看看