August 30, 2017 · clojurescript frontend

Create javascript class with prototype methods in clojurescript

When working with clojurescript, you may need to integrate with javascript codebase that asks you to provide a javascript class. Here's how to create such thing:

(defprotocol IProvider
  (getData [this cbk] "Just bark")
  (watch [this offset limit] "Just bark"))

(deftype RankProvider [name] IProvider
         (getData [this cbk] (println "getData!"))
         (watch [this offset limit] (println "watch!")))

When you access that class with javascript, there would be a problem.

let p = new RankProvider("game");
p.getData(); // This would cause error

clojurescript compiled methods to something like LeaderBoard$core$IProvider$getData$arity$2

(Object.assign (.. RankProvider -prototype)
               #js {"getData" (fn [cbk] (this-as this (getData this cbk)))
                    "watch" (fn [offset limit] (this-as this (watch this offset limit)))})
(Object.assign (.. RankProvider -prototype) (.. EventEmitter -prototype))
  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket