Reputation: 4020
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?)
Upvotes: 2
Views: 225
Reputation: 2353
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
Upvotes: 1