LexiFi / ocaml-vdom

Elm architecture and (V)DOM for OCaml
MIT License
197 stars 13 forks source link

Feature request: add support for a command callback in the update functions #39

Open tcoopman opened 3 years ago

tcoopman commented 3 years ago

Bucklescript-tea has Tea_cmd.call which allows you to enqueue callbacks for example in the update of the model.

This makes handling callbacks from websockets for example much easier. A Ws implementation could look something like this:

let update model = function
  | `Join -> 
    let () = Vdom.Cmd.call (fun callbacks -> Ws.Channel.join model.channel (fun msg -> callbacks.enqueue (`Joined msg)) in
    return model
  | ....
)
tcoopman commented 3 years ago

I've found a way to simulate this:

type 'msg Vdom.Cmd.t += Run of (('msg -> unit) -> unit)

let update model = function
  | `Async ->
        return
          model
          ~c:
            [ Run (fun send -> send `Msg)]

let cmd_handler ctx = function
  | Run cb ->
      cb (fun x -> Vdom_blit.Cmd.send_msg ctx x) ;
      true
  | _ ->
      false

let () = Vdom_blit.(register (cmd { f = cmd_handler }))

Still it would be nice to have this as a build-in option