How to access properties of a keypress event in ClojureScript using pipes?
Using ClojureScript, I am trying to take action when someone clicks enter
into a textbox and ignores other keys. So I need to be able to distinguish between different keystrokes.
For reference, mine is ns
in mine .cljs
:
(ns calculator.calculator
(:require-macros [cljs.core.async.macros :refer [go]])
(:require [goog.dom :as dom]
[goog.events :as events]
[cljs.core.async :refer [put! chan <!]]
[clojure.string :as string]))
There is an input element in my html <input id="data-entry-box"></input>
. I created a listener this way:
(defn listen [el type]
(let [out (chan)]
(events/listen el type
(fn [e] (put! out e)))
out))
(let [keypresses (listen (dom/getElement "data-entry-box") "keypress")]
(go (while true
(let [key-event (<! keypresses)
char-code (.-charCode key-event)]
(.log js/console (str "The character code is " char-code))
(.log js/console (str "The key is " (.-key key-event)))
(.log js/console (str "The event is " (.-event key-event)))
(.log js/console (str "Or the event is " (:event key-event)))
(if (= char-code
13)
(handle-submit))))))
After compiling, loading the page and hitting enter on the input element, I get the following in the console:
"The character code is 13"
"The key is "
"The event is "
"Or the event is "
It's fine; I can check what the key is by looking at the ASCII value, but I don't need to. I would like to access the pressed character.
If I put a breakpoint, I can see that a property exists .event
and that property has one more property .key
. But for some reason, I cannot access it.
source to share
Take a look at the mousetrap code - https://github.com/ccampbell/mousetrap/blob/master/mousetrap.js
Usually keycode is used or matches it manually to "Enter".
Also I have a big doubt. event_ is a generic property, you can refer to https://developer.mozilla.org/en-US/docs/Web/Events/keypress
source to share
The property is not actually called on the keyboard .event
; it's called .event_
. Pay attention to the underscore. Thus, we access it with the (.-event_ key-event)
following:
(let [keypresses (listen (dom/getElement "data-entry-box") "keypress")]
(go (while true
(let [key-event (<! keypresses)
key-pressed (.-key (.-event_ key-event))]
(.log js/console (str "The key pressed was " key-pressed))
(if (= key-pressed
"Enter")
(handle-submit))))))
This code prints: "The key was pressed Enter".
Note that javascript doesn't have character literals, so it returns a (.-key (.-event_ key-event))
string "Enter"
.
source to share