on ghcjs-dom-debug help sign in
reflex-dom/FAQ.md
31 lines 1.6 kB history raw
1# Frequently Asked Questions
3### How do I configure DOM events with flags like `preventDefault` and `stopPropagation`?
5Using `element`, a low-level DOM builder function. Its second argument, `ElementConfig`, has a `_elementConfig_eventSpec` field that can be modified using `addEventSpecFlags`. It takes a `Proxy` that specifies the `DomSpace`, an event name, and a callback which takes the event result and returns an event flag, which can enable behavior like `preventDefault` and `stopPropagation`.
7The type signature on `def` is needed because the fields of the `ElementConfig` can change the type of the `ElementConfig`. GHC can probably figure out the type of the resulting `ElementConfig`, but it doesn't know what the type of `def` was before the modifications, since it never gets used with that configuration.
9For example:
11```haskell
12{-# LANGUAGE OverloadedStrings #-}
13{-# LANGUAGE ScopedTypeVariables #-}
15import Control.Lens ((&), (%~), (.~))
16import Data.Proxy
17import Reflex.Dom
19main :: IO ()
20main = mainWidget $ do
21 (click, ()) <- linkPreventDefault $ text "reflex-frp"
22 display =<< count click
24linkPreventDefault :: forall t m a. DomBuilder t m => m a -> m (Event t (), a)
25linkPreventDefault c = do
26 let cfg = (def :: ElementConfig EventResult t (DomBuilderSpace m))
27 & elementConfig_initialAttributes .~ ("href" =: "https://reflex-frp.org")
28 & elementConfig_eventSpec %~ addEventSpecFlags (Proxy :: Proxy (DomBuilderSpace m)) Click (const preventDefault)
29 (link, a) <- element "a" cfg c
30 return (domEvent Click link, a)
31```