LoginSignup
6
1

More than 5 years have passed since last update.

【Elm】特定のキーボードキーを押した時にイベントを発火させる

Last updated at Posted at 2018-05-04

Enterを押した時にイベントを発火(JavaScript)

例えばJavaScriptだと以下のように書ける。

<textarea class="button"></textarea>
let obj = document.querySelector('.button')
obj.addEventListener('keypress', onKeyPress)


function onKeyPress(e) {
  if ( e.keyCode === 13) {
    alert(e.keyCode)  
  }
  return
 }

Enterを押した時にイベントを発火(Elm)

ElmのHtml.Eventsではkeypressのようなイベントハンドラがない。

代わりにCustom DecodersであるKeyCodeを使うことで実現することが出来る。

-- Json Decodeをimport
import Json.Decode as Json


type Msg = Enter Int


update : Msg -> Model -> ( Model, Cmd Msg)
update msg model =
      case msg of
            Enter key ->
                 case key of
                     13 -> ...


view : Model -> Html Msg
view model =
    textarea [ onKeyPress Enter ] []


-- onKeyPressはInt(押されたキー)とMsg(Enter)を引数にとりMsg(Enter)を発行
onKeyPress : (Int -> Msg) -> Attribute Msg
onKeyPress tagger =
    Html.Events.on "keypress" (Json.map tagger Html.Events.keyCode)
6
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
1