Add date constructor

This commit is contained in:
Sendil Kumar 2018-06-26 16:52:56 +02:00
parent f9ae7f49ad
commit ef27cb6392
3 changed files with 41 additions and 8 deletions

View File

@ -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<FnMut()>, 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

View File

@ -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.
///

View File

@ -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()