2

I have an array of objects in my Javascript file that I need to access from js_of_ocaml. I've come up with this so far:

let table_decks = (Js.Unsafe.variable "table_decks" :> 
  < deck_nr : int > Js.js_array Js.t)

In Javascript, the array will be like table_decks = {{deck_nr: 10, ...}, {deck_nr: 20, ...}} with more fields than just deck_nr.

My question is: How do I access this array? I find a lot of functions in Js.js_array, but no get/set.

(Another question is if the coerce is in fact correct?)

1 Answer 1

1

Use Js.array_get/array_set or Js.Unsafe.get/set.

val array_get : 'a #js_array t -> int -> 'a optdef
val array_set : 'a #js_array t -> int -> 'a -> unit

To support overloading on ocaml, js_of_ocaml removes letters after last _ in javascript name. So "deck_nr" becames "deck" in generated js, so add another "_".

Put all it together...

let table_decks = (Js.Unsafe.variable "table_decks" :>
  < deck_nr_ : int Js.prop > Js.t Js.js_array Js.t)

let get a n =
  match Js.Optdef.to_option (Js.array_get a n) with
  | Some n -> n##deck_nr_
  | None -> 0
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.