Skip to content

Instantly share code, notes, and snippets.

@krisleech
Created April 16, 2018 09:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krisleech/3c67c7769fde67dfae689004dbb85c84 to your computer and use it in GitHub Desktop.
Save krisleech/3c67c7769fde67dfae689004dbb85c84 to your computer and use it in GitHub Desktop.
[Clojure] Event dispatch example

Generic function which take a handler function and calls it passing in a event map. Typically this will be used with partial to create a dispatch function which is bound to a handler.

(defn dispatch [handler message] 
  (let [event (json/read-str message)]
    (println "<- dispatch" event "to" handler) 
    (handler event)))

A handler, this just prints the event

(defn event-handler [event] (println event))

A function which wraps our handler, allowing us to pass a raw JSON message, but the handler gets an event map.

(def event-dispatch (partial dispatch event-handler))

This is how it is called, we would typically hook this up to a stream of JSON events coming from a message bus or websocket.

(def json (json/write-str { :name "hello" }))

(event-dispatch json)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment