Building The Frontend With ClojureScript by Daniel Jaouen

2018-02-01

I recently spent some time building out the frontend of this website using ClojureScript. In particular, I used Secretary and cljs-ajax. I just wanted to clarify some points of contention so that you might benefit from my mistakes. 😀

First, since Clojure is a functional language, variables cannot be “updated”. Instead, if you need to “update” a variable, you need to use one of Clojure’s three “state” paradigms: refs, atoms, and agents. I ended up going with atoms to build out my ClojureScript generated html. I basically doseq over my collection of items (posts, comments, etc.) and swap! in the newly generated html.

Next, since callbacks lose the context of their caller, I had to “close over” some functions like so:

(defn comment-button-callback-wrapper [slug]
  (let [comment-form (by-id "comment_form")]
    (fn [evt]
      (.preventDefault evt)
      (POST (str "/api/posts/" slug)
            :body (js/FormData. comment-form)
            :handler comment-button-post-handler
            )
      )
    )
  )

As you can see, the slug variable is “closed over” in this example.

You can see the updated frontend in action here. Let me know what you think!

Comment

Back