From ef27cb63925089c6f60f648ea93e4bf97ed5d008 Mon Sep 17 00:00:00 2001 From: Sendil Kumar Date: Tue, 26 Jun 2018 16:52:56 +0200 Subject: [PATCH] Add date constructor --- examples/closures/src/lib.rs | 15 +++++++-------- src/js.rs | 8 ++++++++ tests/all/js_globals/Date.rs | 26 ++++++++++++++++++++++++++ 3 files changed, 41 insertions(+), 8 deletions(-) diff --git a/examples/closures/src/lib.rs b/examples/closures/src/lib.rs index b4917845..de4b04ea 100644 --- a/examples/closures/src/lib.rs +++ b/examples/closures/src/lib.rs @@ -3,6 +3,8 @@ extern crate wasm_bindgen; use wasm_bindgen::prelude::*; +use wasm_bindgen::js::Date; +use wasm_bindgen::js::JsString; #[wasm_bindgen] extern { @@ -16,13 +18,6 @@ extern { #[wasm_bindgen(js_name = setInterval)] fn set_interval(cb: &Closure, delay: u32) -> f64; - // Bindings for JS `Date` so we can update our local timer - type Date; - #[wasm_bindgen(constructor)] - fn new() -> Date; - #[wasm_bindgen(method, js_name = toLocaleString)] - fn to_locale_string(this: &Date) -> String; - // Bindings for `document` and various methods of updating HTML elements. // Like with the `dom` example these'll ideally be upstream in a generated // crate one day but for now we manually define them. @@ -57,7 +52,11 @@ pub fn run() { update_time(); fn update_time() { document.get_element_by_id("current-time") - .set_inner_html(&Date::new().to_locale_string()); + .set_inner_html( + &String::from( + Date::new() + .to_locale_string( + JsString::from("en-GB"), JsValue::undefined()))); } // We also want to count the number of times that our green square has been diff --git a/src/js.rs b/src/js.rs index daa45dce..4e090c74 100644 --- a/src/js.rs +++ b/src/js.rs @@ -377,6 +377,14 @@ extern { extern { pub type Date; + /// Creates a JavaScript Date instance that represents + /// a single moment in time. Date objects are based on a time value that is + /// the number of milliseconds since 1 January 1970 UTC. + /// + /// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date + #[wasm_bindgen(constructor)] + pub fn new() -> Date; + /// The toDateString() method returns the date portion of a Date object /// in human readable form in American English. /// diff --git a/tests/all/js_globals/Date.rs b/tests/all/js_globals/Date.rs index 930c59df..82ed7009 100644 --- a/tests/all/js_globals/Date.rs +++ b/tests/all/js_globals/Date.rs @@ -2,6 +2,32 @@ use super::project; +#[test] +fn new() { + project() + .file("src/lib.rs", r#" + #![feature(proc_macro, wasm_custom_section)] + + extern crate wasm_bindgen; + use wasm_bindgen::prelude::*; + use wasm_bindgen::js::Date; + + #[wasm_bindgen] + pub fn new_date() -> Date { + Date::new() + } + "#) + .file("test.ts", r#" + import * as assert from "assert"; + import * as wasm from "./out"; + + export function test() { + assert.equal(typeof wasm.new_date(), "object"); + } + "#) + .test() +} + #[test] fn to_date_string() { project()