How to filter a list based on user input with ClojureScript and Om?

大憨熊 提交于 2019-12-21 12:18:56

问题


I just started to use Om (a reactjs based library for ClojureScript). I would like to filter a list based on user input. The following works but the solution seems to be to complicated. Is there a better one ?

(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:


I think that this is a better solution:

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


来源:https://stackoverflow.com/questions/23179779/how-to-filter-a-list-based-on-user-input-with-clojurescript-and-om

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!