Skip to content

Commit

Permalink
Make dispatch async.
Browse files Browse the repository at this point in the history
WARNING: not tested.
  • Loading branch information
mike-thompson-day8 committed Dec 20, 2014
1 parent 310f79a commit d733c9c
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 6 deletions.
1 change: 1 addition & 0 deletions project.clj
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

:dependencies [[org.clojure/clojure "1.6.0"]
[org.clojure/clojurescript "0.0-2371"]
[org.clojure/core.async "0.1.346.0-17112a-alpha" :scope "provided"]
[reagent "0.4.3"]
[historian "1.0.7"]]

Expand Down
35 changes: 29 additions & 6 deletions src/re_frame/handlers.cljs
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
(ns re-frame.handlers
(:require-macros [cljs.core.async.macros :refer [go-loop]])
(:require [re-frame.db :refer [app-db]]
[re-frame.utils :refer [first-in-vector]]))
[re-frame.utils :refer [first-in-vector]]
[cljs.core.async :refer [chan put! <!]]))


;; -- register of handlers ------------------------------------------------------------------------

(def ^:private id->fn (atom {}))


Expand All @@ -15,17 +19,36 @@
assoc event-id handler-fn))


;; -- dispatching and routing ---------------------------------------------------------------------

(def ^:private dispatch-chan (chan))

(defn dispatch
"reagent components handle events by calling this function.
"reagent components send events by calling this function.
Usage example:
(dispatch [:delete-item 42])"
[event-v]
(let [event-id (first-in-vector event-v)
handler-fn (get @id->fn event-id)]
(assert (not (nil? handler-fn)) (str "No event handler registered for event: " event-id ))
(handler-fn app-db event-v)))
(assert (some? event-v)) ;; nil would close the channel
(put! dispatch-chan event-v))


(defn- router
"route an event, arriving on the dispatch channel, to the right handler"
[]
(go-loop []
(let [event-v (<! dispatch-chan)
event-id (first-in-vector event-v)
handler-fn (get @id->fn event-id)]
(assert (not (nil? handler-fn)) (str "No event handler registered for event: " event-id ))
(handler-fn app-db event-v)
(recur))))

(router) ;; run the router loop it


;; -- helper --------------------------------------------------------------------------------------

;; TODO: this has to go.
(defn transaction!
"A helper fucntion to be used when writting event handlers.
Allows a handler to perform an atomic modification of the atom.
Expand Down

0 comments on commit d733c9c

Please sign in to comment.