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.
Instructor: [00:00] In this lesson, we start out with a fresh Rust webpack template. Then we add the js-sys dependency to our Cargo.toml. In our Rust file, we declare that we use js-sys, and now, this allows us to use Javascript APIs inside Rust.
[00:19] The example I want to show is updating the welcome message by displaying the current time at the end. We first create a new timestamp, represented as a float using Javascript Date.now function. Next up, we create the new date based on this float value.
[00:42] This data object has multiple methods that we label, like getHours and getMinutes. That's great, because we can leverage them to do some string interpolation, and generate our welcome message. We switch over to the browser and check our results.
[01:01] As expected, we see "Hello from Rust," including the current time. Isn't it amazing, with almost no effort, we can access Javascript APIs from Rust? This not only works in the browser, but also in Node.
Member comments are a way for members to communicate, interact, and ask questions about a lesson.
The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io
Be on-Topic
Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.
Avoid meta-discussion
Code Problems?
Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context
Details and Context
Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!