每个人都在谈论core.async有多棒,以及如何改进clojurescript中的事件处理。我一直在关注ClojureScript 101教程,我没有看到这些代码示例有任何明显的优势。我错过了什么?
为什么在这里更好地使用core.async?
(defn listen [el type]
(let [out (chan)]
(events/listen el type
(fn [e] (put! out e)))
out))
(defn dosomethingasync
[e]
(js/console.log "async: " e))
(let [clicks (listen (dom/getElement "search1") "click")]
(go (while true (dosomethingasync (<! clicks)))))
VS
(defn dosomethingcallback
[e]
(js/console.log "callback: " e))
(events/listen (dom/getElement "search2") "click" dosomethingcallback)
答案 0 :(得分:33)
很棒的问题!
我认为,了解优势的第一步是Timothy Baldridge Video
在我的尝试之下:
我认为如果我们改变你的代码,差异就会消失。
首先,尝试突出显示句子“当组件或子系统必须停止直接相互通信时,所有优秀程序中都会有一段时间”从{{}发布的core.async中提取{3}}。我认为我们可以将输入事件通道与let fn:
分开(def clicks (listen (dom/getElement "search1") "click"))
(go
(while true
(dosomethingasync (<! clicks))))
(put! clicks "this channel can be written from differents parts of your code")
其次,使用core.async,我们可以编写异步调用,因为我们将编写同步调用(顺序代码)。这种情况的一个例子需要多个频道:
(def clicks (listen (dom/getElement "search1") "click"))
(def keys-pressed (listen (dom/getElement "search1") "keypress"))
(def to-out (chan))
(go
(while true
(let [click-recieved (<! clicks)]
(dosomethingasync click-recieved)
(>! to-out "click recieved!")
(let [other-input-waited (<! keys-pressed)]
(dosomethingwithkey other-input-waited)
(>! to-out "keypressed recieved!")
)
)
))
最后,我认为你没有正确使用回调函数的含义。当我们谈论回调函数时,我认为我们指的是一个函数,除了它自己的参数外,它还接收一个函数“callback”。在函数执行结束时,我们调用回调函数将执行流程返回到原始点。 更改“回调”功能如下:
(defn dosomethingcallback
[e call-back-fn]
(js/console.log "callback: " e)
(call-back-fn))
如果我们尝试发布类似于以前的代码core.async示例所实现的相同行为:
(defn do-key
[call-back-fn e]
(.log js/console "before callback key" )
(call-back-fn e))
(defn do-click
[call-back-fn e]
(.log js/console "before callback click")
(call-back-fn e))
(defn key-callback-fn [e]
(.log js/console (str "doing some work with this key: " e))
)
(defn click-callback-fn [e]
(.log js/console (str "doing some work with this click" e))
(events/listen (dom/getElement "search2") "keypress" (partial do-key key-callback-fn)))
(events/listen (dom/getElement "search2") "click" (partial do-click click-callback-fn))