Fork me on GitHub
#reagent
<
2018-05-21
>
theeternalpulse10:05:28

I'm trying to use the r/track as it's outlined in the docs to trigger window events and have it clean-up on component unload soI have this

(defn key-code
  "Returns pointer to currently pressed key"
  []
  (r/with-let [key-pointer (r/atom nil)
               event "onkeypress"
               handler (fn [k]
                         (do
                           (js/console.log "####tracked hit" k)
                           (reset! key-pointer k)))
               _ (.addEventListener js/document event handler)]
    @key-pointer
    (finally
      (.removeEventListener js/document event handler))))

(defn letter-button
  "Renders a button displaying the key
  and playing an audio clip if clicked"
  [{:keys [key clip]} key-code]
  (let [audio (when clip (js/Audio. clip))
        _ @(r/track key-code)]
    (fn []
      [:div {:class 'letter
             :on-click (when clip #(play-pause audio))}
       (char->str key)])))
But having the @(r/track key-code) let binding makes my code blow up without any specific errors. Removing it renders fine.

theeternalpulse11:05:04

I guess maybe event lifecycles would be a better fit?

gadfly36113:05:45

@theeternalpulse at first glance, I don't think you're meant to use r/with-let and finally outside of a reagent component. The function key-code isn't a reagent component, so that's probably why it is blowing up. If you merged the content of key-code in to letter-button, it may work for you.

theeternalpulse13:05:59

which seems to externalize the current state of the event in a separate function, and tracks it inside a component

theeternalpulse13:05:54

The very last example, I'll try the first one in that section, which seems to be what it may be expecting

theeternalpulse13:05:47

that seemed to do it 😕 not arguing with results

theeternalpulse13:05:13

(defn letter-button
  "Renders a button displaying the key
  and playing an audio clip if clicked"
  [{:keys [key clip]} key-code]
  (r/with-let [audio (when clip (js/Audio. clip))
               key-pointer (r/atom nil)
               handler (fn [k]
                         (do
                           (js/console.log "####tracked hit" k)
                           (reset! key-pointer k)))
               _ (.addEventListener js/document "keypress" handler)]
  [:div {:class 'letter
         :on-click (when clip #(play-pause audio))}
   (char->str key)]
  (finally
    (.removeEventListener js/document "keypress" handler))))

theeternalpulse14:05:36

sweet, thanks @gadfly361 that worked nicely, just had to ensure the click hander was checked properly.

gadfly36119:05:25

@theeternalpulse np, glad you got it working!