A few examples of Foreign Function Interface

Brady Ouren edited this page Nov 2, 2016 · 4 revisions

These were copied from here. I did not test them, but just added them here thinking they might be useful. They might be outdated

{-# LANGUAGE JavaScriptFFI      #-}
{-# LANGUAGE OverloadedStrings  #-}

import qualified GHCJS.Types    as T
import qualified GHCJS.Foreign  as F

foreign import javascript unsafe "window.onload = $1" onload :: T.JSFun a -> IO ()
foreign import javascript unsafe "alert($1)" alert :: T.JSString -> IO ()

main = do
  callback <- F.syncCallback F.AlwaysRetain True $ do
    alert "hello world"
  onload callback
{-# LANGUAGE JavaScriptFFI      #-}
{-# LANGUAGE OverloadedStrings  #-}

import qualified GHCJS.Types    as T
import qualified GHCJS.Foreign  as F

foreign import javascript unsafe "window.onload = $1" onload :: T.JSFun a -> IO ()
foreign import javascript unsafe "alert($1)" alert :: T.JSString -> IO ()

main = do
  callback <- F.syncCallback F.AlwaysRetain True $ do
    alert "hello world"
  onload callback
{-# LANGUAGE JavaScriptFFI      #-}
{-# LANGUAGE OverloadedStrings  #-}

import qualified GHCJS.Types    as T
import qualified GHCJS.Foreign

foreign import javascript unsafe "alert($1)" alert :: T.JSString -> IO ()
foreign import javascript unsafe "try { $r = $1.length } catch (nigiritubusu) { $r = null }" js_unsafeLength :: T.JSRef a -> T.JSNumber
foreign import javascript unsafe "\"\"+$1" js_toString :: T.JSRef a -> T.JSString

js_is_shigo_sabaki_ni_au :: T.JSRef a -> IO ()
js_is_shigo_sabaki_ni_au = alert . js_toString . js_unsafeLength

main = do
  js_is_shigo_sabaki_ni_au ("answer to life the universe and everything" :: T.JSString)
  js_is_shigo_sabaki_ni_au T.nullRef
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.