Fork me on GitHub
#clojurescript
<
2020-07-19
>
J17:07:02

Hi everyone! I have a question about cljs/eval.. if I run eval on a "defn f ..." in my web app, and then eval the expr "(f ...)" it works! So it is saved somewhere. I thought maybe in the cljs/state object but I pass an empty one in each time. Also interestingly, the console logs a warning "undeclared Var cljs.user/f" but it still works. So my question is - where is the cross-call data being stored? How is it possible to invoke f on a separate call? And can I access this state?

phronmophobic18:07:39

I think it's just using the cljs.user.f value. If you type window.cljs.user.f into the console, does it show a value? If you change window.cljs.user.f to another value, does the call still work?

J18:07:52

Ah this is exactly what I wanted to know. I didn't realize there was a window.cljs object for program state. But I can also eval "(dmacs.api/f ..)" and that will call a function f that I defined in the namespace. So eval has access to all program namespaces and functions through this window object?

phronmophobic18:07:40

when you compile without advanced optimizations, the values defined in namespaces are all stored at my.namespace.def_name, eg. dmacs.api/f => window.dmacs.api.f

J18:07:13

Wow thank you so much. When I do get to optimizations, is there a way to preserve these namespaces?

phronmophobic18:07:11

in general, yes, you can use ^:export, https://clojurescript.org/reference/advanced-compilation#access-from-javascript eg:

(defn ^:export square [x]
  (* x x))

phronmophobic18:07:35

i'm not sure if cljs eval is supported with advanced optimizations

phronmophobic18:07:23

if you can, I would highly recommend avoiding eval usage in clojurescript

phronmophobic18:07:15

https://clojurescript.org/reference/bootstrappingf you can't avoid eval, you can check out https://clojurescript.org/reference/bootstrapping and there's a #bootstrapped-cljs channel

phronmophobic18:07:12

using eval in cljs is neat, but its usage has several caveats and it will dramatically increase the size of your shipped js

J18:07:34

Ah I see, it's definitely unavoidable for my application but this is good to know