Search code examples
javascriptclojureclojurescript

calling javascript Object from ClojureScript


I want to instantiate a class in javascript, pass the object over to my ClojureScript, and access its properties and functions from Clojure. How can I access the functions and properties of test-obj when I only have clojure.core namespace at my disposal?

I have the following awful hacked solution.

Javascript:

class Test {
  constructor (a,b) {
    this.a = a;
    this.b = b;
  }
  getA () {
    return this.a;
  }
}

window['createA'] = (a,b) => {
  return new Test(a,b);
}

window['geta'] = (o) => {
  return o.getA();
}

ClojureScript:

(defn myfn[] 
  (let [test-obj (.createTest js/window "x" 1)]
  [:div (.geta js/window test-obj)]))

Solution

  • Regular JS interop should work just fine I believe :)

    Expose your class to the outside world:

    window["Test"] = Test
    

    Then, from cljs:

    (let [x (js/Test.)]
      (prn (.getA x)))