How to call Haskell from Javascript with GHCJS

前端 未结 2 1330
耶瑟儿~
耶瑟儿~ 2021-02-01 19:00

I\'ve been playing about with GHCJS. The FFI can be used to call javascript from Haskell but I can\'t figure out how do go the other way round. Say I had a super useful utility

2条回答
  •  旧巷少年郎
    2021-02-01 19:46

    Here's an example that shows how to call a Haskell function from Javascript. This is similar to the example provided by Joachim but compiles and runs with the latest ghcjs.

    import GHCJS.Marshal(fromJSVal)
    import GHCJS.Foreign.Callback (Callback, syncCallback1, OnBlocked(ContinueAsync))
    import Data.JSString (JSString, unpack, pack)
    import GHCJS.Types (JSVal)
    
    sayHello :: String -> IO ()
    sayHello name = print $ "hello, " ++ name
    
    sayHello' :: JSVal -> IO ()
    sayHello' jsval = do
        Just str <- fromJSVal jsval
        sayHello $ unpack str
    
    foreign import javascript unsafe "js_callback_ = $1"
        set_callback :: Callback a -> IO ()
    
    foreign import javascript unsafe "js_callback_($1)" 
        test_callback :: JSString -> IO ()
    
    main = do
        callback <- syncCallback1 ContinueAsync sayHello'
        set_callback callback
        test_callback $ pack "world"
    

    The test works by calling from Haskell into Javascript code that then calls back into Haskell. The variable, "js_callback_", becomes available within Javascript for use as a function that takes one string argument.

提交回复
热议问题