Fork me on GitHub
#re-frame
<
2017-12-27
>
zalky16:12:55

@carkh: I'm curious how you're approaching :window/resize events, because I'm working on something similar ATM. I have components that need to resize whenever the window does. I provide a reactive subscription:

(def <-window-resize
  "Window resize signal. Prefer subscription, do not use directly."
  (r/atom nil))

(defn on-window-resize
  "Window resize event handler. Add once to window on startup."
  [_]
  (->> (.-innerWidth js/window)
       (reset! <-window-resize)))

(f/reg-sub-raw :window/resize
  (fn [_ [_ f node]]
    (r/reaction @<-window-resize (f @node))))
Where a components can provide an arbitrary function f:
(r/with-let [node (r/atom nil)]
  @(f/subscribe [:window/resize resize-fn node])
  [:div ...])
This works great, though the :window/resize subscription performs side-effects. It's not clear from the re-frame documentation whether subscriptions with side-effects are frowned upon, and what the negative implications of subscriptions with side-effects might be. There are clearly side-effects here: https://github.com/Day8/re-frame/blob/master/docs/Subscribing-To-External-Data.md Though not in the actual reaction. I'm curious what approach you took using events.

carkh22:12:47

@zalki: In my case I mostly need the :window/resized event for an impure effect... Let's see if i can make a code block in slack

(ns ss.window ...)

(rf/reg-event-fx
 :window/resized
 (fn [{:keys [db]} [_ {:keys [width height]}]]
  ;we're only interested in width and height
   (let [size {:width width :height height}] 
     {:db (assoc-in db [::window :size] size)
      :phaser.game/resize size})))

(defn dispatch-resize []
  (rf/dispatch [:window/resized {:width (.-innerWidth js/window) :height (.-innerHeight js/window)}]))

(defn add-resize-listener []
  (.addEventListener js/window "resize" dispatch-resize)
  (dispatch-resize))

(ns ss.phaser.game ...)

(defonce game (atom nil))

(defn resize [game width height]
  (.setGameSize (.-scale game) width height))

(rf/reg-fx
 :phaser.game/resize
 (fn [{:keys [width height]}] 
   (when @game
     (resize @game width height))))