reactive-banana: How to create an AddHandler?

馋奶兔 提交于 2019-12-03 23:54:26

newAddHandler is used like this:

do (addHandler, fire) <- newAddHandler
   ...

addHandler is the AddHandler to pass to reactive-banana, and fire is a function of type a -> IO () (where a is your event type) that triggers the event.

For instance, you would likely install fire as the callback to GLFW's mouse-button event, like so:

registerMouseButton :: IO (Event MouseButton)
registerMouseButton = do
  (addHandler, fire) <- newAddHandler
  setMouseButtonCallback $ \button _ -> fire button
  fromAddHandler addHandler

(I'm not experienced with GLFW, so I'm not sure what the second argument to setMouseButtonCallback's callback is — if it's important, you'll need to amend this implementation appropriately.)

An AddHandler is just a function which takes a callback — a -> IO () — and registers it for the event in question; it then returns (from within IO) an IO () action used to deregister this handler, making the complete definition of AddHandler read as follows:

type AddHandler a = (a -> IO ()) -> IO (IO ())

So where does newAddHandler come in? Simple: newAddHandler maintains a list of handlers for an event, and activates them when fire x is executed.

You don't need newAddHandler if, like GTK+ and many other common toolkits, your toolkit already has facilities to register and deregister multiple event handlers; if it does, you should write your own implementation of an AddHandler. But if all it supports is a single callback, you should use newAddHandler.

Note that you never need to expose AddHandlers to the FRP-using code itself; they're just internal glue used to create Events from external inputs.

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