Last active
October 30, 2020 00:31
-
-
Save didibus/66341279d840fc184d7a6a8764b82b5b to your computer and use it in GitHub Desktop.
Example of a simple ClojureScript implementation of a counter, using no dependencies.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#clojurescript-counter |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Run in Klipse
Press Ctrl+Enter if you get an error. For some reason Klipse needs to double compile for the defmulti to work.