Created
April 3, 2019 17:38
-
-
Save michaeljones/0bb4ffabcdf97b3c757004449009ce43 to your computer and use it in GitHub Desktop.
Elm Browser.application example with an attempted 'preventDefault'
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Main exposing (main) | |
import Browser | |
import Browser.Navigation | |
import Html exposing (..) | |
import Html.Attributes exposing (..) | |
import Html.Events exposing (preventDefaultOn) | |
import Json.Decode as Json | |
import Url exposing (Url) | |
type alias Model = | |
{ count : Int, key : Browser.Navigation.Key } | |
initialModel _ _ key = | |
( { count = 0, key = key }, Cmd.none ) | |
type Msg | |
= UrlChange Url.Url | |
| UrlRequest Browser.UrlRequest | |
| Increment | |
| Decrement | |
update : Msg -> Model -> ( Model, Cmd Msg ) | |
update msg model = | |
case msg of | |
UrlChange url -> | |
( model, Cmd.none ) | |
UrlRequest request -> | |
case request of | |
Browser.Internal url -> | |
( model | |
, Browser.Navigation.pushUrl model.key (Url.toString url) | |
) | |
Browser.External url -> | |
( model | |
, Browser.Navigation.load url | |
) | |
Increment -> | |
( { model | count = model.count + 1 }, Cmd.none ) | |
Decrement -> | |
( { model | count = model.count - 1 }, Cmd.none ) | |
view : Model -> Browser.Document Msg | |
view model = | |
{ title = "" | |
, body = | |
[ div [] | |
-- This is the important bit. When you click on this link it still loads http://www.example.com when | |
-- I think it should be prevented? | |
[ a [ href "http://www.example.com", onClickPreventDefault Increment ] [ text "+1" ] | |
, div [] [ text <| String.fromInt model.count ] | |
] | |
] | |
} | |
onClickPreventDefault : msg -> Attribute msg | |
onClickPreventDefault msg = | |
preventDefaultOn "click" <| Json.succeed ( msg, True ) | |
main : Program () Model Msg | |
main = | |
Browser.application | |
{ init = initialModel | |
, view = view | |
, update = update | |
, onUrlChange = UrlChange | |
, onUrlRequest = UrlRequest | |
, subscriptions = \_ -> Sub.none | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment