Skip to content

Bindings with requires #66

@Aaylor

Description

@Aaylor

Considering a javascript library containing a module A with only one static
function called foo taking a string and returning an int. This library
has to be required before usage, but I did not found anything about require in
the documentation.

The first implementation I made was:

module A : sig
  type t
  val require_a : unit -> t
    [@@js.custom let require_a () = Helpers.require "A" ]
  val foo : t -> string -> int
end

To call the function foo in ocaml code, I have to write:

let module_a = A.require_a () in
let i = A.foo module_a "bar" in
...

But I'd like to get rid of the require line. This require would be done lazily into the
module, allowing the user to write directly let i = A.foo "bar" to call the
function.

My first thought was to do something like:

module A : sig
  [@@@js.implem
    let mod_a = ref None
    let get_a () =
      match !mod_a with
      | Some m -> m
      | None ->
        let m = Helpers.require "A" in
        mode_a := Some m;
        m
  ]
  val foo : string -> int
  [@@js.custom
    let foo str =
      let m = get_a () in
      let r = Ojs.call m "foo" [|(Ojs.string_to_js str)|] in
      Ojs.int_of_js r ]
end

But it becomes very annoying to write this when the javascript library has many
methods. What would be the best way to do this kind of things ? Does it match
the philosophy of javascript bindings ?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions