2017-03-09 103 views
1

我经常发现自己定义了clojurescript中的名称空间,它只包含通过def或defn创建的一个var,我将在该名称空间之外使用它。clojure/clojurescript中的单个var命名空间的命名约定是什么?

这在使用时尤为常见,我在其中定义我的组件在单独的文件/名称空间中,而且我只在名称空间外使用这些单个组件。

(ns project.components.component-name) 
(defn component-name ...) 

于是我进口他们这样,我觉得它非常重复性和不明确的,因为是同时用于命名空间和组件一个名字:

project.components.component-name :as [component-name] 

component-name/component-name 

或劣:参考(因为它是那么明显该变种来自另一个命名空间的)

project.components.component-name :refer [component-name] 

component-name 

我知道,有在ECMAScript中这一个有用的模式:

export default function() { ... }; 

那么在Clojure中有这样的事情吗?或者也许有一些确定的公约呢?

以下是我最近开始使用的约定,我对此非常不确定。

(ns project.components.component-name) 
(defn _ ...) 

project.components.component-name :as [component-name] 

然后用它作为

component-name/_ 

回答

1

下划线通常用于你不Clojure中关心的值那么我强烈建议您避免使用_作为函数名。例如,你经常会看到这样的野生代码:

;; Maybe when destructuring a let. Kinda contrived example. 
(let [[a _ _ d] (list 1 2 3 4)] 
    (+ a d 10)) 

;; Quite often in a protocol implementation where we don't care about 'this'. 
(defrecord Foo [] 
    SomeProtocol 
    (thing [_ x] 
    (inc x))) 

没有错,通过具有在命名空间中的单个变种是,虽然我可能会只介绍一个命名空间时,有功能性的合理份额。你可以尝试一个像my-app.components这样的名字空间,在那里你保留所有的小点位,直到它们足够大以保证一个专门的空间。东西沿线:

(ns my-app.components 
    ;; The profile stuff is really big lets say. 
    (:require [my-app.components.profile :as profile])) 

(defn- items->ul 
    [items] 
    [:ul (map #(vector :li (:text %)) items)]) 

(defn- render-nav 
    [state] 
    [:nav (-> state deref :nav-items items->ul)]) 

(defn- render-footer 
    [state] 
    [:footer (-> state deref :footer-items items->ul)]) 

(defn render-layout 
    [state] 
    [:html 
    [:head [:title (:title @state)]] 
    [:body 
    [:main 
    (render-nav state) 
    (profile/render-profile (-> state deref :current-user)) 
    (render-footer state)]]]) 
1

我不知道每个命名空间的一个组件是最好的方法。这将导致 在大量的命名空间和相当多的重复。然而,这是 clojure和每个人都有不同的风格。我的方法是使用命名空间 来分解功能。除了最简单的 组件之外,我发现组件不会使用其他组件也很少见。我倾向于将特定功能中使用的所有组件和用于大多数其他组件的各种低级组件组合在一起,并具有/ utility /或/ base /名称空间。例如,我可能 有类似

project --| 
      src --| 
       my-app --| 
         core.cljs 
         interface --| 
            base.cljs 
            navbar.cljs 
            sidebar.cljs 
            tabber.cljs 

在每一个这些命名空间中,可能有多个组件。其中一些可能被定义为对该名称空间是私有的,而其他的是 被core.cljs引用的条目组件。我发现命名空间需要部分不要太大 大或重复,我不需要在不同的文件中跳转多达 YMMV。