Skip to content

Instantly share code, notes, and snippets.

@miyamoen
Last active May 21, 2019 13:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miyamoen/08740930e498fab4aaa882a77900dafe to your computer and use it in GitHub Desktop.
Save miyamoen/08740930e498fab4aaa882a77900dafe to your computer and use it in GitHub Desktop.
UrlChangedをとめる
{
"type": "application",
"source-directories": [
"."
],
"elm-version": "0.19.0",
"dependencies": {
"direct": {
"elm/browser": "1.0.1",
"elm/core": "1.0.2",
"elm/html": "1.0.0",
"elm/json": "1.1.3",
"elm/url": "1.0.0",
},
"indirect": {
"elm/virtual-dom": "1.0.2"
}
},
"test-dependencies": {
"direct": {},
"indirect": {}
}
}
module PreventUrlChange exposing (init, update)
import Browser exposing (Document, UrlRequest(..))
import Browser.Navigation as Nav exposing (Key)
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events
import Json.Decode as JD
import Url exposing (Url)
type alias Model =
Key
type Msg
= NoOp
| ClickedLink UrlRequest
| UrlChanged Url
main : Program () Model Msg
main =
Browser.application
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
, onUrlRequest = ClickedLink
, onUrlChange = UrlChanged
}
init : () -> Url -> Key -> ( Model, Cmd msg )
init _ _ key =
( key, Cmd.none )
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
NoOp ->
( Debug.log "NoOp" model, Cmd.none )
ClickedLink (Internal url) ->
( model
, Nav.pushUrl model (Debug.log "onUrlRequest: Internal" <| Url.toString url)
)
ClickedLink (External url) ->
( model
, Nav.load (Debug.log "onUrlRequest: External" url)
)
UrlChanged url ->
let
_ =
Debug.log "onUrlChange" url
in
( model, Cmd.none )
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.none
view : Model -> Document Msg
view model =
{ title = "Prevent onUrlRequest"
, body =
[ div [ preventUrlRequest ]
[ a [ href "#div" ]
[ span []
[ text "outside event listener" ]
]
]
, div []
[ a [ href "#a", preventUrlRequest ]
[ span []
[ text "self event listener" ]
]
]
, div []
[ a [ href "#span" ]
[ span [ preventUrlRequest ] -- 内側にpreventDefaultとstopPropagationを有効にしたイベントリスナーをはるとonUrlRequestは発火しない
[ text "inside event listener" ]
]
]
]
}
preventUrlRequest : Attribute Msg
preventUrlRequest =
Html.Events.custom "click"
(JD.succeed
{ message = NoOp
, stopPropagation = True
, preventDefault = True
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment