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:

  • define a type with methods in it using deftype.
(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

  • Now you need to define those method on class's prototype.
(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)))})
  • In case you need to extend some other class using clojurescript, getting methods from other class's prototype is required.
(Object.assign (.. RankProvider -prototype) (.. EventEmitter -prototype))