Search code examples
clojureclojurescriptluminus

ClojureScript function is always executed


I'm learning ClojureScript, I have two functions that just change the content in the "root-app" div:

(ns blog.core)

 (defn mount-components []
   (let [content (js/document.getElementById "root-app")]
     (while (.hasChildNodes content)
       (.removeChild content (.-lastChild content)))
     (.appendChild content (js/document.createTextNode "Wilkommen zu mein 
     ekelhaft blog!!"))))

 (defn init! []
   (def current_url js/window.location.href)
   (if (clojure.string/includes? current_url "about")
     (.log js/console (str "Whatever URL ->>>" js/window.location.href))
     (mount-components)))

All works fine in http://localhost:3000/about because the "root-app" div exists in that page, but in http://localhost:3000/blog, I get the error message:

enter image description here

Because there is no such div in that page. All this is weird because it looks like ClojureScript in fact finds that:

 (if (clojure.string/includes? current_url "about")

is actually false en the console.log is not printed.

My question is: why the function mount-components runs and sends the error message even when the conditional if is false? The weird thing is that the console.log:

 (.log js/console (str "Whatever URL ->>>" js/window.location.href))   

doesn't run but mount-components function does. I guess I'm not understanding the "sequence" in the way that ClojureScript works.


Solution

  • I'm not sure, but by your description, I think the logic you are thinking of and the logic you are actually testing are not the same. Your if statement looks for the word 'about' in the URL. If it is there, then it prints the console log i.e. it will be there for http://localhost:300/about. If it is NOT there, it will run the mount-components function, which looks for the div ID which you say is not included on the page, so you get the error. the mount-components is an ELSE statement and is therefore executed when the test is false.