Big-Bang mouse move

big-bang

Demonstration of using Big-Bang: reactively capturing a stream of mouse move events

25 Jan 2014 by rm-hull
rm-hull/8617788
BIGBANG_MOUSE_DEMO.md

Move the mouse around to see a demonstration of Big-Bang mouse-move event handling. Big-bang uses core.async to handle events in a reactive manner, dispatching to relevant state-handlers so that manipulating state occurs in a purely functional manner.

In the code below, the update function is only fired when a new mouse-move event is delivered to big-bang’s event loop. It is passed the event and the current ‘world-state’, of which it returns a modified version. The render function is invoked on a javascript requestAnimationFrame() callback only if the world state has been changed.

Big-bang is a new library, and is subject to ongoing change, but supports a flexible architecture which allows:

  • Reactive handling of browser events
  • Interval timer for periodic firings
  • Interaction with any DOM elements (originally targetted against <canvas>, but as demonstrated below there is no restriction)
  • Interaction with the outside world via core.async channels - specifically other big-bang loops - refer to the relevant Racket documentation for an idea how this works.

Compare and contrast to the equivalent Om version: http://programming-enchiladas.destructuring-bind.org/rm-hull/8617445

bigbang_mouse_demo.cljs
(ns examples.mouse.core
  (:require [big-bang.core :refer [big-bang]]
            [big-bang.events.browser :refer [client-coords]]
            [dommy.core :refer [insert-after!]])
  (:use-macros [dommy.macros :only [sel1 node]]))

(->> 
  (sel1 :#canvas-area)
  (insert-after! (node [:div#app])))

(def app (sel1 :#app))

(defn update [event world-state] 
  (assoc world-state :mouse-coords (client-coords event)))

(defn render [world-state]
  (set! 
    (.-innerText app) 
    (pr-str (:mouse-coords world-state))))

(big-bang
  :initial-state {:mouse-coords [0 0]}
  :on-mousemove update
  :to-draw render)