From d0c9d2a1c55f74a71def44db4cd3f66f12ef666c Mon Sep 17 00:00:00 2001 From: Kevan Stannard Date: Thu, 13 May 2021 15:08:28 +1000 Subject: [PATCH] Add %external() class feature detection example --- .../latest/bind-to-global-js-values.mdx | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/pages/docs/manual/latest/bind-to-global-js-values.mdx b/pages/docs/manual/latest/bind-to-global-js-values.mdx index 65038f1bf..58acf4899 100644 --- a/pages/docs/manual/latest/bind-to-global-js-values.mdx +++ b/pages/docs/manual/latest/bind-to-global-js-values.mdx @@ -142,4 +142,36 @@ if (match !== undefined) { +This approach may also be used for JS class feature detection. + +Note that here we are using the `\""` syntax which allows us to [use a capitalized identifier name](./use-illegal-identifier-names). + + + +```res example +type audioContext + +@new external createAudioContext: unit => audioContext = "AudioContext" + +let createAudioContext: unit => option = () => { + switch %external(\"AudioContext") { + | Some(_) => createAudioContext()->Some + | None => None + } +} +``` + +```js +var Caml_option = require("rescript/lib/js/caml_option.js"); + +function createAudioContext(param) { + var match = typeof AudioContext === "undefined" ? undefined : AudioContext; + if (match !== undefined) { + return Caml_option.some(new AudioContext()); + } +} +``` + + +