Idiomatic way of binding eventhandler of js Object

I’d like to bind to js WebSocket object.

So far I came up with this :

type data
type event = {
    data: data
type socket = {
    onmessage: event => unit

@new external createWebSocket: string => socket = "WebSocket"

let ws = createWebSocket("ws://localhost:8000/ws");

Now I’d like give ws.onmessage eventHandler a function but compiler says its immuable so I can’t just write

ws.onmessage = (event) => {/* do something with */}

How should I do it ?

You will need to use a property setter binding: bucklescript-bindings-cookbook/ at master · yawaramin/bucklescript-bindings-cookbook · GitHub

In this case it will look like this:


type t
type messageEvent = {data: string}
type messageEventHandler = messageEvent => unit

@new external new_: string => t = "WebSocket"
@set external set_onmessage: (t, messageEventHandler) => unit = "onmessage"

EDIT: usage looks like:

// In another module

let ws = WebSocket.new_("ws://...")
ws->WebSocket.set_onmessage(({data}) => Js.log(data))