guide: Add section on working with duck-typed interfaces

This commit is contained in:
Nick Fitzgerald 2018-09-11 16:29:44 -07:00
parent a311c29f1d
commit 1872e84a8a
4 changed files with 27 additions and 3 deletions

View File

@ -1,7 +1,6 @@
# Canvas 2D Example
# Duck-Typed Interfaces Example
This directory is an example of using the `web-sys` crate to draw on a 2D
canvas.
This directory is an example of using duck-typed JS interfaces with `wasm-bindgen`.
You can build and run the example with:

View File

@ -15,6 +15,7 @@
- [No ES Modules](./reference/no-esm.md)
- [Arbitrary Data with Serde](./reference/arbitrary-data-with-serde.md)
- [Accessing Properties of Untyped JS Values](./reference/accessing-properties-of-untyped-js-values.md)
- [Working with Duck-Typed Interfaces](./reference/working-with-duck-typed-interfaces.md)
- [Command Line Interface](./reference/cli.md)
- [Supported Types](./reference/types.md)
- [Imported JavaScript Types](./reference/types/imported-js-types.md)

View File

@ -5,6 +5,10 @@ regardless if it is an `instanceof` some JavaScript class or not, use [the
`js_sys::Reflect` APIs][js-sys-reflect]. These APIs are bindings to the
[JavaScript builtin `Reflect` object][mdn-reflect] and its methods.
You might also benefit from [using duck-typed
interfaces](./working-with-duck-typed-interfaces.html) instead of working with
untyped values.
## Reading Properties with `js_sys::Reflect::get`
[API documentation for `js_sys::Reflect::get`.](https://rustwasm.github.io/wasm-bindgen/api/js_sys/struct.Reflect.html#method.get)

View File

@ -0,0 +1,20 @@
# Working with Duck-Typed Interfaces
Liberal use of [the `structural`
attribute](./attributes/on-js-imports/structural.html) on imported methods,
getters, and setters allows you to define duck-typed interfaces. A duck-typed
interface is one where many different JavaScript objects that don't share the
same base class in their prototype chain and therefore are not `instanceof` the
same base can be used the same way.
## Defining a Duck-Typed Interface in Rust
```rust
{{#include ../../../examples/duck-typed-interfaces/src/lib.rs}}
```
## JavaScript Usage
```js
{{#include ../../../examples/duck-typed-interfaces/duck-typed-interfaces.js}}
```