How to pass state between event handlers in gtk2hs

笑着哭i 提交于 2019-12-03 00:20:42

First off, you could have a global. Ignoring that solution as bad form, this looks like a job for an MVar. In main you just make a new MVar which you can update in onKeyboard and check in myDraw:

...
import Control.Concurrent.MVar

main = do
    ...
    mv <- newMVar 0
    ....
    canvas `on` exposeEvent $ do liftIO $ renderWithDrawable draWin (myDraw mv 10)
    ...
    window `on` keyPressEvent $ onKeyboard canvas mv

onKeyboard canvas mv = do
    modifyMVar_ mv (\x -> return (x + 1))
    ....

myDraw mv pos = do
    val <- readMVar mv
    ...

Note that sharing mutable state is also often useful when passing functions as arguments by first using partial application to provide the MVar (or TVar, IORef, whatever).

Oh, and a warning: MVars aren't strict - if the application has the potential to write lots without forcing the value (i.e. reading and comparing the contained Int), then you should force the value before writing to avoid building a huge thunk.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!