How to pass state between event handlers in gtk2hs

后端 未结 1 1954
挽巷
挽巷 2021-02-04 15:36

I\'m trying to make a toy application, just to get my head around how to write event driven programs in Haskell. What I\'m trying to do is draw a line to a canvas which moves fo

相关标签:
1条回答
  • 2021-02-04 16:23

    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.

    0 讨论(0)
提交回复
热议问题