Render without allocating ratom unless necessary

This commit is contained in:
Dan Holmsand 2014-02-10 15:29:38 +01:00
parent 51ac2be955
commit 8f1c02b273
3 changed files with 36 additions and 18 deletions

View File

@ -128,16 +128,22 @@
(do-render C))
res)))))
(defn run-reactively [C run on-dirty]
(let [rat (.-cljsRatom C)]
(if (nil? rat)
(let [res (ratom/capture-derefed run C)
derefed (.-captured C)]
(when (and (not (nil? derefed))
tmpl/isClient)
(set! (.-cljsRatom C)
(ratom/make-reaction run
:auto-run on-dirty
:derefed derefed)))
res)
(ratom/run rat))))
(defn reactive-render [C]
(assert C)
(when (nil? (.-cljsRatom C))
(set! (.-cljsRatom C)
(ratom/make-reaction
#(do-render C)
:auto-run (if tmpl/isClient
#(queue-render C)
identity))))
(ratom/run (.-cljsRatom C)))
(run-reactively C #(do-render C) #(queue-render C)))
;;; Function wrapping
@ -179,7 +185,9 @@
:componentWillUnmount
(fn [C]
(ratom/dispose! (.-cljsRatom C))
(let [ratom (.-cljsRatom C)]
(if-not (nil? ratom)
(ratom/dispose! ratom)))
(set! (.-cljsIsDirty C) false)
(when f (f C)))

View File

@ -4,11 +4,13 @@
(declare ^:dynamic *ratom-context*)
(def debug false)
(def -running (clojure.core/atom 0))
(defn running [] @-running)
(defn- capture-derefed [f obj]
(defn capture-derefed [f obj]
(set! (.-captured obj) nil)
(binding [*ratom-context* obj]
(f)))
@ -115,7 +117,7 @@
(when (not= derefed watching)
(-update-watching this derefed))
(when-not active?
(swap! -running inc)
(when debug (swap! -running inc))
(set! active? true))
(set! dirty? false)
(set! state res)
@ -142,7 +144,7 @@
(set! state nil)
(set! dirty? true)
(when active?
(swap! -running dec)
(when debug (swap! -running dec))
(set! active? false))
(when on-dispose
(on-dispose)))
@ -159,8 +161,14 @@
IHash
(-hash [this] (goog/getUid this)))
(defn make-reaction [f & {:keys [auto-run on-set on-dispose]}]
(let [runner (if (= auto-run true) run auto-run)]
(Reaction. f nil true false
nil {}
runner on-set on-dispose)))
(defn make-reaction [f & {:keys [auto-run on-set on-dispose derefed]}]
(let [runner (if (= auto-run true) run auto-run)
active (not (nil? derefed))
dirty (not active)
reaction (Reaction. f nil dirty active
nil {}
runner on-set on-dispose)]
(when-not (nil? derefed)
(when debug (swap! -running inc))
(-update-watching reaction derefed))
reaction))

View File

@ -6,6 +6,8 @@
(:require [cemerick.cljs.test :as t]
[reagent.ratom :as rv]))
(set! rv/debug true)
(defn running [] (rv/running))
(defn dispose [v] (rv/dispose! v))