Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Example of a simple ClojureScript implementation of a counter, using no dependencies.
(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
(cl-format nil
<div>Count: ~a</div>
<button onclick=\"counter.core.msg('increment')\">+</button>
<button onclick=\"counter.core.msg('decrement')\">-</button>
<button onclick=\"counter.core.msg('increment-by', 10)\">+10</button>
<button onclick=\"counter.core.msg('decrement-by', 10)\">-10</button>
;;;; Beginner Program Framework
(defn -redraw [html]
(set! (.-innerHTML js/klipse-container)
(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))
Copy link

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