How do you reference javascript's this keyword from clojurescript? - clojurescript

I'm integrating some ClojureScript code with a JS library call that takes a callback function. The JS library passes data to the callback using JavsScript's "this" keyword.
I can get it to work using (js* "this"). For example:
(libraryCall (fn [] (.log console (js* "this"))))
Is there a way to get at the "this" context from ClojureScript without resorting to js*?

Use the built-in this-as macro. It takes a name and a body, and evaluates the body with the name bound to JavaScript this.
e.g.
(libraryCall (fn [] (this-as my-this (.log js/console my-this))))
Great question... had to dig into the compiler code to find it, it's not well advertised at all.
I'll add it to the book.

Related

Failed to construct ‘HTMLElement’: Please use the ‘new’ operator

I am trying to use AWS Amplify Authentication lib in a re-frame app.
The lib provides a higher order component withAuthenticator which is supposed to wrap the main view of your app. I am trying to use reactify-component and adapt-react-class but unfortunately I get the following error:
Uncaught TypeError: Failed to construct ‘HTMLElement’: Please use the ‘new’ operator, this DOM object constructor cannot be called as a function.
(defn main-panel []
[:div
[:h1 "Hello" ]])
(def root-view
(reagent/adapt-react-class
(withAuthenticator
(reagent/reactify-component main-panel))))
(defn ^:dev/after-load mount-root []
(re-frame/clear-subscription-cache!)
(aws-config/configure)
(re-frame/dispatch-sync [::events/initialize-db])
(reagent/render [root-view]
(.getElementById js/document "app")))
Any help is appreciated
I had this issue with reagent + amplify.
Solved it with 2 changes, but I'm unsure if both are needed
#1 Change output of the google closure compiler to es6 (or higher). Amplify seems to use es6 features that Cannot be polyfilled.
This is for shadow-cljs (shadow-cljs.edn), but this should be possible for other build systems as well.
{:builds {:app {:compiler-options {:output-feature-set :es6}}}}
Disclaimer: I switched to shadow-cljs from lein-cljsbuild since I could not get lein-cljsbuild to respect the configuration for es6 output.
#2 Use functional components.
In reagent 1.0.0-alpha1 and up you can change the compiler to produce functional components by default.
(ns core
(:require
[reagent.core :as r]))
(def functional-compiler (r/create-compiler {:function-components true}))
(r/set-default-compiler! functional-compiler)
There are other ways to make functional components. Check the documentation if you don't like, or can't use, this approach.

Getting props in reagent's :reagent-render function

I Javascript's version of react I can use
this.props
but what can I use to gave props in
:reagent-render
callback?
I am trying to do as done here in Chart.js line 14.
To answer your question, you can access the component and props in reagent-render by doing something like this
(ns chartly.core
(:require
[reagent.ratom :as ra]
[reagent.core :as r]))
(defn data-fn [implicit-this]
;; use implicit-this as needed, which is equivalent to "this"
;; From create-class docs -
;; :component-did-mount (fn [this])
)
(defn chart-render []
(let [comp (r/current-component) ;; Reagent method
r-props (r/props comp) ;; Reagent method
js-props (.-props (clj->js comp))]
(js/console.log "PROPS" r-props) ;;-- etc...
[:div {:style {:width 100}}]))
(def data (ra/atom {})) ;;--> see more info on reagent-atom
(defn chart-component []
(r/create-class
{:component-did-mount data-fn
:display-name "chart-component"
:reagent-render chart-render}))
To use -
[chart-component]
However, this is anti-pattern and will be quite difficult to manage, since you are trying to update data prop internally with component-did-mount, which, on completion, would need to manually signal the React component to update itself.
One of the features of Reagent is that is offers to detect changes and updating the component, usually using atom. See Managing State in Reagent for more info.
What you are looking to do is exactly what the Re-frame Framework is helping to manage. You set-up a data-store, and when the store changes, it signals to subscribers (React elements) to update accordingly, and you don't have to handle the signal changes yourself.
There are some edge cases where tapping into the lifecyle events are necessary, especially with charts and other drawing libraries, but I might recommend re-visiting if you find reagent atoms and/or the re-frame library insufficient for your needs. Hope this helps.
As far as I see, you accept some Hiccup data from a user as a string, right? And then try to evaluate it into user namespace, where only reagent library is loaded?
First, the more you build your further code to evaluate, the more difficult to understand it becomes. You could use something like this:
(binding [*ns* user-ns] (eval (read-string user-data)))
Also, to prevent wrong input, it would be better to validate user's input either with Schema or clojure.spac libraries. Since read-string returns a data structure, it might be checked with those two as well. So you would see an error before starting to evaluate something.

equivalent of $(document).ready(function(){}) in clojurescript?

how implement $(document).ready(function(){}) in clojurescript.
I tried this:
(. ready js/document ());;but i am trying to achieve the callback function
But doesn't seem right to me. Any ideas?
new to clojurescript so i am bit confused as to how to do this.
This should work:
(.addEventListener
js/window
"DOMContentLoaded"
(fn [] (.log js/console "DOMContentLoaded callback")))
For simply a clojurescript entry point, you may implement a main function in e.g. the core namespace:
(ns app.core)
(defn main []
(activate-app))
Then call the entry point at the end of the module:
(main)
The idea is to have the entry point main function called after all code has been loaded. Hence the module with the entry point call should not itself be required by any other modules.
A variation sets up an entry point explicitly called from javascript after the compiled clojurescript has been loaded:
(defn ^:export main []
(activate-app))
(set! js/cljs-entry-point main)
This entry point can now be called from a script element at the bottom of the body of the associated html document:
<script>cljs_entry_point()</script>
A benefit with the latter approach is that other modules still can require the module containing the entry point.
Consider a function main which calls a number of other functions.
(defn main []
(app-instruction-1)
(app-instruction-2))
(set! (.-onload js/window) main)

Clojurescript Add an Event Listener

(defn domready [handler]
(.addEventListener js/window "DOMContentLoaded" handler))
I borrowed this code from here. The problem is I don't totally understand what's going on. JS interop is still a bit of a mystery to me.
.addEventListener
So this is clearly a procedure call, but it's kind of generic. It's like Clojurescript took everything that was inside an object, took it out, and you use it to call that method on "objects". As long as that "object" has the ".addEventListener" property it will call this. Is that what it's doing? Why not use a keyword instead? like (:addEventListener domElement) that seems more logical to me.
js/window
What is this? Is it a namespace or an object? Are they the same thing?
"DOMContentLoaded"
A string, that's familiar.
handler
Also familiar, but does it have a notion of this? Not that I'm really going to miss this.
.addEventListener
So this is clearly a procedure call, but it's kind
of generic. It's like Clojurescript took everything that was inside an
object, took it out, and you use it to call that method on "objects".
As long as that "object" has the ".addEventListener" property it will
call this. Is that what it's doing? Why not use a keyword instead?
like (:addEventListener domElement) that seems more logical to me.
Your mental model about how this works is mostly fine. What it does when it compiles is move the function name to be run as a method on the first argument.
(.method obj ...args) get's transformed to obj.method(...args)
This type of interop comes from the parent language Clojure.
On why do we have an explicit version of calling the function that's not Clojure idiomatic, I think the idea is to have clear separation between what is native Clojure code with Clojure semantics (immutability, friendly to CLJ data structures, etc) and what is interoperating with the host environment (mutable, not friendly to CLJ data structures, etc).
In my opinion it is better to have clear separation between those two given how different the semantics of CLJS and the host platforms are. For me explicitness is better than implicit in this case (it is easy to spot looking at the code what is JS code in CLJS, and what is pure CLJS).
js/window
What is this? Is it a namespace or an object? Are they the same thing?
Both, js/ is accessing the namespace js, which is where CLJS puts the JS namespace (since there is only one and global). window is just grabbing the window variable from the js namespace.
This is no different from how you access variables in other namespaces in CLJS. If you (def a 1) in (ns cljs.test) and then run cljs.test/a that will give you 1. Same form, ns/something-in-that-ns.
"DOMContentLoaded"
A string, that's familiar.
\o/
handler
Also familiar, but does it have a notion of this? Not that I'm really going to miss this.
Not sure what this has to do with handler. It is just a higher order function passed into domready as a parameter, like you would do in JS: function domready (onReady) { window.addEventListener("DOMContentLoaded", onReady) }
I hope this helps, if you want to try it out live and learn some more, maybe visit the Talking with JS on the Diving into ClojureScript tutorial, or maybe check this section of the lt-cljs-tutorial.
I'm just learning clojurescript so I don't really know if it is the correct answer but I've done it in the following way:
(defn handler [] (js/console.log "ready"))
(js/document.addEventListener "DOMContentLoaded" handler)
which is then translated to
cljs.user.handler = (function cljs$user$handler(){
return console.log("ready");
});
document.addEventListener("DOMContentLoaded",cljs.user.handler);
to check how clojurescript translate code I've used KLIMPSE http://app.klipse.tech/
.addEventListener is a method call on the global Javascript object js/window. This method call takes two parameters: "DOMContentLoaded" and handler.
When you are doing interop (either Java or Javascript) you really are calling methods on objects. There are macros behind what is happening here. What is straight after the ( is a verb, which I usually think of as a function call (although it might also be a macro or a special form). When doing interop what comes after the verb is the instance, and after that the parameters.
If it were straight Javascript it would look like this:
function domready(handler){
window.addEventListener("DOMContentLoaded" handler);
}

How can I get the Clojurescript namespace I am in from within a clojurescript program?

How can I get the Clojurescript namespace I am in from within a clojurescript program? I want to do this do provide certain debug information (it only needs to work in dev mode)
Namespaces are not first class in ClojureScript as they are in Clojure. There's absolutely no way to get the namespace at runtime. It is possible to get this information at macroexpansion time if you're not afraid of accessing some the ClojureScript compiler internals. There should probably be an API for this - but we're not there yet.
You can get the name of the current namespace with this trick, which takes advantage of :: creating a namespaced symbol for you in the current namespace:
(namespace ::x)
You probably don't want to use that value for anything, because if the code is compiled the internal representation will change. If you want to live dangerously, then in the browser you can then access the js object that holds the namespace like this:
(reduce (fn [ns n] (aget ns n))
js/window
(clojure.string/split (namespace ::x) #"\."))
During macro-expansion you can access &env and retrieve namespace information from the :ns key like this:
(:ns &env)
(:name (:ns &env))
This only works at macro-expansion/compile time and not at runtime.
You can try this
(apply str (drop-last 2 (str `_)))