How can I translate the javascript code to clojurescript?
I would like to use capacitor/app to get the state (background or active) of my app on iOS. My project is based on Clojurescript so it is necessary to translate the following javascript code to clojurescript one.
- Javascript
import { App } from '@capacitor/app';
App.addListener('appStateChange', ({ isActive }) => {
console.log('App state changed. Is active?', isActive);
});
- translated clojurescript
(ns js.sample
(:require ["@capacitor/app" :refer [App]]))
(.addListener App "appStateChange"
#((fn [isActive]
(js/console.log isActive))))
I suppose I would get isActive
as true
or false
, but I constantly get an undefined
output. What is wrong with my code? Appreciate for any help.
Solution 1:
(.addListener App "appStateChange"
(fn [^js event]
(js/console.log (.-isActive event))))
As cfrick's comment mentions, #(...)
is not needed there. #(...)
is basically just a shorthand for (fn [...] ...)
, and you already have a function there.
In JS, {isActive}
in a function's signature means that isActive
will be assigned to the value of the isActive
field of the object that was passed to the function.
^js
in CLJS marks the name that follows it as one containing a JS object. It's necessary to make sure that things like isActive
don't end up being renamed by the compiler during production build optimizations. It shouldn't be necessary in this case because isActive
name is not something that you or some library invented but rather a name coming from JS API. But I still find it to be a good practice to delineate such things. (^js
shouldn't be used with goog
imports, however.)