OM mouse move

om

Demonstration of using Swannodette's OM: reactively capturing a stream of mouse move events.

25 Jan 2014 by rm-hull
rm-hull/8617445
OM_MOUSE_DEMO.md

Move the mouse around the page, and watch as OM reactively sets the co-ordinates. This was slightly modified from David Nolan’s examples at https://github.com/swannodette/om/blob/master/examples/mouse/src/core.cljs to add a <div id="app"></div> programmatically. I imagine there’s an official OM way to splice components into a page, but used Dommy instead … FTW.

Compare and contrast to the equivalent Big-Bang version: http://programming-enchiladas.destructuring-bind.org/rm-hull/8617788

om_mouse_demo.cljs
(ns examples.mouse.core
  (:require-macros [cljs.core.async.macros :refer [go]])
  (:require [goog.events :as events]
            [cljs.core.async :as async :refer [>! <! put! chan]]
            [om.core :as om :include-macros true]
            [om.dom :as dom :include-macros true]
            [dommy.core :refer [insert-after!]])
  (:use-macros [dommy.macros :only [sel1 node]])
  (:import [goog.events EventType]))

; Adjusted slightly from the original to insert an "app" div
(->> 
  (sel1 :#canvas-area)
  (insert-after! (node [:div#app])))

(defn listen [el type]
  (let [out (chan)]
    (events/listen el type #(put! out %))
    out))

(om/root
  {:mouse nil}
  (fn [app node]
    (reify
      om/IWillMount
      (will-mount [_]
        (let [mouse-chan
              (async/map
                (fn [e] [(.-clientX e) (.-clientY e)])
                [(listen js/window EventType/MOUSEMOVE)])]
          (go (while true
                (om/update! app assoc :mouse (<! mouse-chan))))))
      om/IRender 
      (render [_]
        (dom/p nil
          (when-let [pos (:mouse app)]
            (pr-str (:mouse app)))))))
  (.getElementById js/document "app"))