Tracking mouse in clojurescript / reagent / reagi?

99封情书 提交于 2020-02-03 04:30:34

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/42357138/tracking-mouse-in-clojurescript-reagent-reagi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!