如何使用ClojureScript和Om根据用户输入过滤列表? [英] How to filter a list based on user input with ClojureScript and Om?

查看:114
本文介绍了如何使用ClojureScript和Om根据用户输入过滤列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始使用Om(一个基于reactjs的ClojureScript库)。我想根据用户输入过滤列表。以下工作但解决方案似乎是复杂的。有更好的吗?

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


推荐答案

我认为这是一个更好的解决方案:

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

这篇关于如何使用ClojureScript和Om根据用户输入过滤列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆