【发布时间】:2017-10-14 22:34:16
【问题描述】:
我正在学习 ClojureScript,我有两个函数可以改变“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)))
在http://localhost:3000/about 中一切正常,因为该页面中存在“root-app” div,但在http://localhost:3000/blog 中,我收到错误消息:
因为该页面中没有这样的 div。这一切都很奇怪,因为看起来 ClojureScript 实际上发现:
(if (clojure.string/includes? current_url "about")
实际上是 false 并且未打印 console.log。
我的问题是:为什么函数 mount-components 运行并发送错误消息,即使条件 if 为假?奇怪的是console.log:
(.log js/console (str "Whatever URL ->>>" js/window.location.href))
不运行,但 mount-components 功能可以运行。我想我不理解 ClojureScript 工作方式的“序列”。
【问题讨论】:
-
显然
content为空。元素 ID 对吗?这基本上是一个 NPE。 -
将
let替换为when-let以仅在找到元素时运行。见clojuredocs.org/clojure.core/when-let -
你(几乎)永远不应该在函数范围内使用
def,你在init!函数中这样做。def在全局范围内创建一个 var。请改用let的本地绑定。 -
也应该是“Willkommen zu meim ekelhaften Blog”
标签: clojure clojurescript luminus