Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example of a simple ClojureScript implementation of a counter, using no dependencies.
#clojurescript-counter
(ns counter.core
(:require [cljs.pprint :refer [cl-format]]))
;;;; Model
(def model (atom 0))
;;;; Update
(defmulti update
(fn [msg model args] msg))
(defmethod update :increment
[msg model args]
(inc model))
(defmethod update :decrement
[msg model args]
(dec model))
(defmethod update :increment-by
[msg model [by]]
(+ model by))
(defmethod update :decrement-by
[msg model [by]]
(- model by))
;;;; View
(defn view
[model]
(cl-format nil
"
<div>
<div>Count: ~a</div>
<div>
<button onclick=\"counter.core.msg('increment')\">+</button>
<button onclick=\"counter.core.msg('decrement')\">-</button>
</div>
<div>
<button onclick=\"counter.core.msg('increment-by', 10)\">+10</button>
<button onclick=\"counter.core.msg('decrement-by', 10)\">-10</button>
</div>
</div>"
model))
;;;; Beginner Program Framework
(defn -redraw [html]
(set! (.-innerHTML js/klipse-container)
html))
(defn ^:export msg [msg-string & args]
(let [msg (keyword msg-string)
updated-model (update msg @model args)
new-view (view updated-model)]
(reset! model updated-model)
(-redraw new-view)))
(-redraw (view @model))
@didibus
Copy link
Author

didibus commented Jul 15, 2018

Run in Klipse

Press Ctrl+Enter if you get an error. For some reason Klipse needs to double compile for the defmulti to work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment