How can I create a global object, and attach a string and a function to that object, in ClojureScript?

106 views Asked by At

How can I create a global object, attached to the window, and attach a string and a function to that object, in ClojureScript?

For example, an myobject that looks like:

{"foo": function () {..},
 "bar": "somestring"}

myobject.foo => function () { .. }

myobject.bar => "somestring"

2

There are 2 answers

0
hzhu On BEST ANSWER

Here's the JavaScript that generates an object attached to the window. It has too properties. foo which is a function and .bar which is a string.

(let [my-object (set! (.-myobj js/window (clj->js {})))
      some-func (fn [] (+ 1 1))]

  (set! (.-foo my-object) some-func)
  (set! (.-bar my-object) "something"))  
1
Jonas On

I'm not completely sure why you need this, but it's very similar to the Javascript version:

{:foo (fn [] ...)
 :bar "something"}

(:foo my-object) => (fn [] ...)
(:bar my-object) => "something"

There are some important differences between the Clojure and Javascript versions

  1. Clojurescript maps are immutable.
  2. There's no this reference pointing to the "object" in the function body. Clojure maps are not objects, they are key-value pairs.