I'm trying to get to grips with reagent in clojurescript with a simple drawing program.
I'm looking for an example of how to access the mouse position in a principled "FRP" inspired style with Reagi.
In various reagent examples I can see things that look like this :
[:p [:onmousemove (fn (evt) ...)]]
to attach a handler to an element of the DOM.
And to make a Reagi "behaviour" I want to write something like this :
(def mouse-positions (r/behavior ( ... )))
But how do I combine these two so that a handler I add to a DOM element feeds a Reagi behavior?
Secondly, as I'm using reagent, I'm expecting these DOM nodes to be recreated regularly. Presumably I'll need to keep rebinding the event-handler to the Reagi stream too. How do I ensure this?
cheers
I wonder if Reagi's event stream would be better suited. Something along the lines of:
(defonce mouse-events (r/events {:x 0 :y 0}))
(defn home-page []
[:div {:onMouseMove (fn [event]
(r/deliver mouse-events {:x (.-clientX event)
:y (.-clientY event)}))}])
Then, you can deref the event stream with @mouse-events
. You shouldn't need to worry about having to rebind to the event stream as it holds the reference to it.
However, keep in mind that pushing a value into a Reagi stream will not cause Reagent to re-render a node that references it directly. For that you will need some sort of Reagent atom.
If you're creating a drawing application, I imagine your state/atom will be stored elsewhere, and you swap!
or reset!
that to cause the render to occur.
Also, note that both behaviors and events only hold the reference to the newest value, which may not be ideal for a drawing application. There is also Reagi's buffer
that may help with that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With