Как отфильтровать список на основе пользовательского ввода с помощью ClojureScript и Om?

Я только начал использовать Om (библиотека на основе Reactjs для ClojureScript). Я хотел бы отфильтровать список на основе пользовательского ввода. Следующие работы, но решение кажется сложным. Есть ли лучше?

(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"))})

person rogergl    schedule 20.04.2014    source источник


Ответы (1)


Я думаю, что это лучшее решение:

(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"))})
person rogergl    schedule 20.04.2014
comment
Я думаю, что list-data должен быть нечувствительным к регистру. (defn list-data [alist filter-text] (filter #(re-find (js/RegExp. filter-text "i") %) alist)) Когда вы ищете "a", вы получаете: ("Zebra" "Buffalo" "Antelope") источник: заголовок stackoverflow.com/questions/23186490/ - person leontalbot; 21.04.2014