Skip to content

Instantly share code, notes, and snippets.

@escherize
Created May 2, 2016 16:19
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 escherize/3e03c100ea09bbe38f6f764b55b058b0 to your computer and use it in GitHub Desktop.
Save escherize/3e03c100ea09bbe38f6f764b55b058b0 to your computer and use it in GitHub Desktop.
(ns cljs-horizon.app
(:require [reagent.core :as reagent :refer [atom]]
[clojure.string :as str]))
;; horizon library
(def horizon (js/Horizon))
;; db table
(def chat (horizon "messages_four"))
;; function to save into db
(defn save-message [m]
(->> (merge m {:datetime (js/Date.)})
clj->js
(.store chat)))
;; local datastore
(defonce messages (atom #{}))
;; watch the chat table and when we are notified of an update
;; by horizon, update messages to its new value.
(.. chat
(order "datetime" "descending")
(limit 8)
(watch)
(forEach
(fn [x] (->> (js->clj x :keywordize-keys true)
(reset! messages)))))
(defn calling-component []
(let [box (atom "")]
(fn []
(let [submit (fn []
(when (not= "" @box)
(save-message {:text @box})
(reset! box "")))]
[:div
[:h2 "Welcome to Horizon"]
(into [:div] (for [text (mapv :text @messages)]
[:p text]))
[:hr]
[:input {:value @box
:on-change (fn [e] (reset! box (-> e .-target .-value)))
:on-key-press (fn [e]
(let [enter 13]
(if (= enter (.-charCode e))
(submit)))
true)}]
[:button {:on-click submit
:value "Add something."}]]))))
(defn init []
(reagent/render-component [calling-component]
(.getElementById js/document "container")))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment