簡體   English   中英

如何使用ClojureScript和Om基於用戶輸入過濾列表?

[英]How to filter a list based on user input with ClojureScript and 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"))})

我認為這是一個更好的解決方案:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM