如何使用ClojureScript和Om根据用户输入筛选列表?

7

我刚开始使用Om(一种基于ClojureScript的ReactJS库)。我想根据用户输入来过滤列表。以下代码可以实现,但解决方案似乎过于复杂。是否有更好的解决方案?

(ns om-tut.core
  (:require-macros [cljs.core.async.macros :refer [go]])
  (:require [om.core :as om :include-macros true]
            [om.dom :as dom :include-macros true]
            [clojure.string :as string]))

(enable-console-print!)

(def app-state (atom {:list ["Lion" "Zebra" "Buffalo" "Antelope"]}))

(defn handle-change [e owner {:keys [text]}]
  (om/set-state! owner :data (vec (filter (fn [x] (> (.indexOf x(.. e -target -value)) -1)) (@app_state :list))))
  (om/set-state! owner :text (.. e -target -value)))


(defn list-view [app owner]
  (reify
    om/IInitState
    (init-state [_]
      {:text nil
       :data (:list app)
       })
    om/IRenderState
    (render-state [this state]    
      (dom/div nil
        (apply dom/ul #js {:className "animals"}
          (dom/input 
            #js {:type "text" :ref "animal" :value (:text state)
                 :onChange #(handle-change % owner state)})               
          (map (fn [text] (dom/li nil text)) (:data state)))))))


(om/root list-view app-state
  {:target (. js/document (getElementById "registry"))})
1个回答

2
我认为这是一个更好的解决方案:
(ns om-tut.core
  (:require-macros [cljs.core.async.macros :refer [go]])
  (:require [om.core :as om :include-macros true]
            [om.dom :as dom :include-macros true]))

(def app-state (atom {:list ["Lion" "Zebra" "Buffalo" "Antelope"]}))

(defn handle-change [e owner {:keys [text]}]
  (om/set-state! owner :text (.. e -target -value)))

(defn list-data [alist filter-text]
 (filter (fn [x] (if (nil? filter-text) true
                     (> (.indexOf x filter-text) -1))) alist))

(defn list-view [app owner]
  (reify
    om/IInitState
    (init-state [_]
      {:text nil})
    om/IRenderState
    (render-state [this state]
      (dom/div nil
        (apply dom/ul #js {:className "animals"}
          (dom/input
            #js {:type "text" :ref "animal" :value (:text state)
                 :onChange (fn [event] (handle-change event owner state))})
            (map (fn [text] (dom/li nil text)) (list-data (:list app) (:text state)))))))) 

(om/root list-view app-state
  {:target (. js/document (getElementById "animals"))})

1
我认为list-data应该不区分大小写。(defn list-data [alist filter-text] (filter #(re-find (js/RegExp. filter-text "i") %) alist))当您查找“a”时,您会得到:("Zebra" "Buffalo" "Antelope") 来源:https://dev59.com/YH7aa4cB1Zd3GeqPwOff?noredirect=1#comment35464719_23186490 - leontalbot

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接