7

I'm looking for a way to define Clojurescript functions in the Javascript global namespace at compile time. What I mean by compile-time is that I want the Clojurescript compiler to output this: function some_fn() { }. I know that this is not idiomatic and everything should reside in a namespace but the environment that I'm in forces me to do this. So, ideally something like (defn ^:global some-fn []) that would work similar to how :export works but ignores the namespace.

I'm aware of the runtime method for defining global functions using goog.global, e.g (set! goog.global.someFunction some-clojure-fn) but this doesn't work in my environment.

4
  • 2
    Are you aware that if you annotate your function with ^:export you can refer to it directly from javascript? e.g. my.name.space.some_fn() Commented Mar 27, 2013 at 10:42
  • Yes I am. I'm afraid that I really want it to be a top level function because I can't deal with the name.space.prefix stuff. Commented Mar 27, 2013 at 12:07
  • Kanaka's answer is what you're after then. Window is where top-level stuff lives. Commented Mar 27, 2013 at 19:48
  • some javascript environments don't provide any sort of global object, which means we need to generate var foo = "bar" - is this possible? Commented Nov 14, 2013 at 15:39

2 Answers 2

8

Perhaps you could define it in a namespace and then expose it in the window (or GLOBAL or this depending on your environment) object:

(defn foo [x] (* 2 x))
(aset js/window "foo" myns/foo)  ;; where myns is where foo is defined

You should then be able to call foo from the window (which is the global JavaScript namespace in the browser).

Update: As suggested by @TerjeNorderhaug, you can set a variable in the global namespace like this:

(set! js/foo foo)
Sign up to request clarification or add additional context in comments.

1 Comment

Alternatively set the global with (set! js/foo foo)
3

Setting a javascript var to an anonymous Clojurescript function will define the compiled function in the Javascript global namespace:

(set! js/some_fn (fn []))

Calling the function works as expected:

(js/some_fn)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.