From a3c88750e5b95b755e55a66145639200233734a3 Mon Sep 17 00:00:00 2001 From: mike-thompson-day8 Date: Sat, 21 Feb 2015 00:47:01 +1100 Subject: [PATCH] Re-work handlers, routers and dispatchers. More comments --- src/re_frame/handlers.cljs | 113 ++++++++++++++++++++----------------- 1 file changed, 60 insertions(+), 53 deletions(-) diff --git a/src/re_frame/handlers.cljs b/src/re_frame/handlers.cljs index 2968341..b7f295d 100644 --- a/src/re_frame/handlers.cljs +++ b/src/re_frame/handlers.cljs @@ -7,81 +7,88 @@ [cljs.core.async :refer [chan put! fn (atom special-handlers)) - +(def ^:private id->fn (atom {})) (defn register "register a handler for an event" [event-id handler-fn] - (if (contains? @id->fn event-id) - (println "Warning: overwritting an event-handler" event-id)) ;; TODO: more generic logging - (swap! id->fn - assoc event-id handler-fn)) + (when (contains? @id->fn event-id) + (warn "Overwriting an event-handler" event-id)) ;; allow it, but warn. + (swap! id->fn assoc event-id handler-fn)) -;; -- dispatching and routing --------------------------------------------------------------------- +;; -- The Event Conveyor Belt -------------------------------------------------------------------- +;; A channel which moves events from dispatch to handlers. +;; +;; 1. "dispatch" puts events onto this chan, and +;; 2. "router" reads from the chan, and calls associated handlers +;; This enables async handling of events -- which is a good thing. +(def ^:private event-chan (chan)) -(def ^:private dispatch-chan (chan)) -(defn dispatch - "components send events by calling this function. - Usage example: - (dispatch [:delete-item 42])" - [event-v] - (assert (some? event-v)) ;; nil would close the channel - (put! dispatch-chan event-v)) +;; -- router -------------------------------------------------------------------------------------- -(defn dispatch-sync - "sync version of above that actually does the dispatch" +(defn- handle + "Look up the handler for the given event, then call it, passing in 2 parameters." [event-v] (let [event-id (first-in-vector event-v) handler-fn (get @id->fn event-id)] - (assert (some? handler-fn) (str "No event handler registered for event: " event-id )) - (handler-fn app-db event-v))) + (if (nil? handler-fn) + (warn "No event handler registered for event: " event-id ) + (handler-fn app-db event-v)))) -(defn- router - "route an event, arriving on the dispatch channel, to the right handler" - [] - (go-loop [] - (let [ ;; if a small pause is required (dispatch [:flush-reagent]) - _ (if @wait-one-annimation-frame - (do - (reset! wait-one-annimation-frame false) - (