代码之家  ›  专栏  ›  技术社区  ›  nha

浏览器功能-检查ClojureScript中是否存在对象

  •  3
  • nha  · 技术社区  · 11 年前

    测试ClojureScript中是否存在某些内容的方法是什么?例如,我正在尝试访问浏览器地理位置API。在javascript中,我会这样做一个简单的检查:

    // check for Geolocation support
    if (navigator.geolocation) {
      console.log('Geolocation is supported!');
    }
    else {
      console.log('Geolocation is not supported for this Browser/OS version yet.');
    }
    

    但将其转换为ClojureScript时,我会遇到一个错误:

    (if (js/navigator.geolocation)  ;; Uncaught TypeError: navigator.geolocation is not a function
       (println "Geolocation is supported")
       (println "Geolocation is not supported"))
    

    检查ClojureScript中浏览器功能的正确方法是什么?

    2 回复  |  直到 11 年前
        1
  •  7
  •   ClojureMostly    9 年前

    有多个选项:

    1. exists? : http://dev.clojure.org/jira/browse/CLJS-495

    仅存在于clojurecriptionpt中,而不存在于clojure中。 如果您查看宏 in core.cljc 你会发现这只是一个 if( typeof ... !== 'undefined' ) . 示例用法:

       (if (exists? js/navigator.geolocation)
          (println "Geolocation is supported"))
          (println "Geolocation is not supported"))
    
    1. (js-in "geolocation" js/window) 扩展到 "geolocation" in windows .

    2. (undefined? js/window.geolocation) 扩展到 void 0 === window.geolocation

    IMO,正确的是 js-in .

        2
  •  1
  •   nha    11 年前

    目前,我正在使用:

    (if (not (nil? js/navigator.geolocation))
        (println "Geolocation is supported")
        (println "Geolocation is not supported"))
    

    不确定这个习惯用法是否涵盖所有用例,我很乐意接受另一个有适当解释的答案。