Skip to content

Instantly share code, notes, and snippets.

@auramo
Last active March 15, 2017 11:03
Show Gist options
  • Save auramo/a2e515973b4168396dd1 to your computer and use it in GitHub Desktop.
Save auramo/a2e515973b4168396dd1 to your computer and use it in GitHub Desktop.
ClojureScript Protocol and Deftype View example
(defprotocol View
"View abstraction"
(render [this some-param] "Renders view")
(destroy [_] "Destroys view, runs cleanup"))
(deftype ProjectView [data]
View
(render [this some-param] [:h1 (str "Hello " (:name data) " some param we passed in " some-param)])
(destroy [_] (println "Cleaning up")))
(def my-instance (ProjectView. {:name "Cuicca"}))
(render my-instance "yeah")
;; -> [:h1 "Hello Cuicca some param we passed in yeah"]
(destroy my-instance)
;; -> "Cleaning up"
;; Let's call render with something else than instance of View/ProjevtView:
(render {} "yeah")
;; -> Error: No protocol method View.render defined for type cljs.core/PersistentArrayMap: {}
;; Let's call render in another namespace:
(ns other)
(render {} "yeah")
;; -> TypeError: Cannot read property 'call' of undefined
;; Let's create an anonymous instance:
(defn create-anon-view [data]
(reify View
(render [this some-param] [:h1 (str "Hello " (:name data) " some param we passed in " some-param)])
(destroy [_] (println "Cleaning up"))))
(def av (create-anon-view {:name "Cuiccis"}))
(render av "we are legion")
;; -> [:h1 "Hello Cuiccis some param we passed in we are legion"]
;; NOTE: render etc. needs to be :referred if we are using the view instance in another namespace
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment