Skip to content

Instantly share code, notes, and snippets.

@jackrusher
Last active September 30, 2017 07:23
Show Gist options
  • Save jackrusher/89e199d1e682aeb6eaa4e9db6d777e61 to your computer and use it in GitHub Desktop.
Save jackrusher/89e199d1e682aeb6eaa4e9db6d777e61 to your computer and use it in GitHub Desktop.
;; A `cell` is a special kind of variable that acts like a spreadsheet cell, sending updates along to every place it is referenced, updating and re-computing along the way.
(defcell circle-size 16)
;; Here's a small view contains a slider and a circle that responds to the slider:
(cell
(html [:div
[:h2 "Adjustable Circle"]
[:input {:type "range"
:on-input #(reset! circle-size
(-> % (.-currentTarget) (.-value) int))}]
[:div (colorize "aqua" (circle @circle-size))]]))
;; Note that both the `circle-size` cell's reported value and the circle itself change when you move the slider. This happens because the function attached to `on-input` is `reset!`ing the `circle-size`, which then communicates that change to every cell that depends on it.
;; We can use this same mechanism to store reactive state for an application, for example by placing a `map` with multiple entries in a cell:
(defcell some-state
{:size 20
:colors ["magenta" "cyan" "yellow"]})
;; ... then assigning some behavior that updates what's in the state map. For example, when you click on this circle it will change its size *and* color:
(cell (->> (colorize (first (@some-state :colors))
(circle (@some-state :size)))
(listen :click #(swap! some-state assoc :size (+ 20 (rand-int 10))
:colors (shuffle (@some-state :colors))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment