Search code examples
javascripthaskellreactive-extensions-jsrxjsghcjs

GHCJS: How do I import a high order javascript function using FFI?


How do I import in GHCJS a Javascript function like the following ?

xs.subscribe(function(x) { console.log(x) })

I tried various combinations of the following without success:

data Observable_
data Disposable_

type Observable a = JSRef Observable_
type Disposable = JSRef ()

foreign import javascript unsafe "$1.subscribe($2)"
  rx_subscribe :: Observable a -> JSRef (a -> IO()) -> IO Disposable

Any help is appreciated, and links to documentation of the GHCJS FFI.

Thanks


Solution

  • Thanks to the guys on the GHCJS IRC Channel I got the answer:

    foreign import javascript safe "$1.subscribe($2)"
      rx_subscribe :: Observable a -> JSFun (a -> IO()) -> IO Disposable
    
    subscribe :: FromJSRef a => (a -> IO()) -> Observable a -> IO Disposable
    subscribe f xs = syncCallback1 True True f' >>= rx_subscribe xs
                     where f' x = fromJSRef x >>= f . fromJust
    

    Thank You