2015-08-21 15 views
0

我使用cemerick/url构造我的URL的ajax请求。 但是,查询的一些参数来自异步本机回调。所以,我把一切都放在一个go块,如下所示:ClojureScript - 构建url有条件地在去块

(defn myFn [options] 
    (go (let [options (cond-> options 
         ;; the asynchronous call 
         (= (:loc options) "getgeo") (assoc :loc (aget (<! (!geolocation)) "coords"))) 

      constructing the url 
      url (-> "http://example.com" 

        (assoc-in [:query :param] "a param") 

        ;; How do I not associate those if they don't exist ? 
        ;; I tried something along the lines of this, but it obviously doesn't work. 
        ;; (cond-> (and 
        ;;   (-> options :loc :latitude not-nil?) 
        ;;   (-> options :loc :latitude not-nil?)) 
        ;; (do 
        ;; )) 
        ;; these will fail if there is no "latitude" or "longitude" in options 
        (assoc-in [:query :lat] (aget (:loc options) "latitude")) 
        (assoc-in [:query :lng] (aget (:loc options) "longitude")) 

        ;; url function from https://github.com/cemerick/url 
        (url "/subscribe") 
        str)]))) 

我希望能够能够通过其中{:loc "local}{:loc {:latitude 12 :longitude 34}}{}作为参数传递给我的功能。 我觉得我没有使用正确的结构。

我该如何构建这个网址?

+0

目前尚不清楚你的问题有'core.async'做什么。你能详细说明一下吗? –

+0

我对你在问什么有点感觉,这可能是一个有趣的问题,但你应该真正清理标题和问题。您的示例代码非常混乱且不清楚。至于你最后的评论:地图似乎是一个合适的数据结构;你有什么担心? –

+0

@NathanDavis好吧,它迫使我把它放在一个'go'块,这(我认为)阻止我使用匿名函数。 – nha

回答

0

如果我明白你的问题吧,你需要的代码,它看起来像这样:

;; helper function 
(defn add-loc-to-url-as [url loc k as-k] 
    (if-let [v (k loc)] 
    (assoc-in url [:query as-k] v) 
    url)) 

;; define function, that process options and extends URL 
(defn add-location [url options] 
    (if-let [location (:loc options)] 
    (if (string? location) 
     ;;; it expects string, for {:loc "San Francisco"} 
     (assoc-in url [:query :location] location) 
     ;;; or map, for {:loc {:latitude 12.123, :longitude 34.33}} 
     (-> url 
      (add-loc-to-url-as location :latitude :lat) 
      (add-loc-to-url-as location :longitude :lng))) 
    url)) 

;; now you can use it in your block 
;; ... 
the-url (-> (url "http://example.com" "subscribe") 
      (assoc-in [:query :param] "a param") 
      (add-location options))