From f850a6fafc6cae76b57601cef891460fb3598064 Mon Sep 17 00:00:00 2001 From: Alexander Kryvomaz Date: Sun, 1 Jul 2018 15:44:36 +0300 Subject: [PATCH] bindings for Function.prototype.bind() --- src/js.rs | 7 ++++++ tests/all/js_globals/Function.rs | 40 ++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/src/js.rs b/src/js.rs index ced943054..e10d8d882 100644 --- a/src/js.rs +++ b/src/js.rs @@ -325,6 +325,13 @@ extern "C" { #[wasm_bindgen(method)] pub fn apply(this: &Function, context: &JsValue, args: &Array) -> Function; + /// The bind() method creates a new function that, when called, has its this keyword set to the provided value, + /// with a given sequence of arguments preceding any provided when the new function is called. + /// + /// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind + #[wasm_bindgen(method)] + pub fn bind(this: &Function, context: &JsValue) -> Function; + /// The length property indicates the number of arguments expected by the function. /// /// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length diff --git a/tests/all/js_globals/Function.rs b/tests/all/js_globals/Function.rs index b54a26299..b5f32d5ba 100644 --- a/tests/all/js_globals/Function.rs +++ b/tests/all/js_globals/Function.rs @@ -38,6 +38,46 @@ fn apply() { .test() } +#[test] +fn bind() { + project() + .file( + "src/lib.rs", + r#" + #![feature(proc_macro, wasm_custom_section)] + + extern crate wasm_bindgen; + use wasm_bindgen::prelude::*; + use wasm_bindgen::js; + + #[wasm_bindgen] + pub fn bind(this: &js::Function, context: &JsValue) -> js::Function { + this.bind(context) + } + "#, + ) + .file( + "test.ts", + r#" + import * as assert from "assert"; + import * as wasm from "./out"; + + export function test() { + const obj = { + a: 0, + fn: function () { + return this.a + 1; + } + } + + const boundFn = wasm.bind(obj.fn, { a: 41 }); + assert.equal(boundFn(), 42); + } + "#, + ) + .test() +} + #[test] fn length() { project()