Over a million developers have joined DZone.

ClojureScript Painkiller (for OOP)

· Java Zone

Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code! Brought to you in partnership with ZeroTurnaround.

When I learned and used ClojureScript, I really hated writing code that looks like this:

(defn Bag []
  (this-as this
           (set! (.-store this) (array))
           this))
 
(set! (.. Bag -prototype -add)
      (fn [val]
        (this-as this
                 (.push (.-store this) val))))
 
(set! (.. Bag -prototype -print)
      (fn []
        (this-as this
                 (.log js/console (.-store this)))))
 
(def mybag (Bag.))
(.add mybag 5)
(.add mybag 7)
(.print mybag)

That’s so much ceremony and repeated waste!

I know it’s not how you’re supposed to write ClojureScript, but sometimes you have to (for example when working with OO libraries).

What do you do with such code? Cover it with macros!

So I wrote two little macros that you can just pick up and use right away in your ClojureScript, so that it can look like:

(defn Bag []
  (this-as this
           (set! (.-store this) (array))
           this))
 
(set-obj-fn Bag.prototype.add [val]
            (.push (.-store this) val))
 
(set-obj-fn Bag.prototype.print [val]
            (.log js/console (.-store this)))

Or just a this-as shortcut:

(set! (.. Bag -prototype -add)
      (obj-fn [val]
        (.push (.-store this) val)))

Source with complete sample is on github. The library is on Clojars, so to use it all you need is [cljs-painkiller "0.1.0"] in your project.cljs. Enjoy!



 

The Java Zone is brought to you in partnership with ZeroTurnaround. Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code!

Topics:

Published at DZone with permission of Konrad Garus , DZone MVB .

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}