2014-04-20 7 views
7

मैंने अभी ओम (क्लोजरस्क्रिप्ट के लिए एक प्रतिक्रिया आधारित लाइब्रेरी) का उपयोग करना शुरू कर दिया है। मैं उपयोगकर्ता इनपुट के आधार पर एक सूची फ़िल्टर करना चाहता हूं। निम्नलिखित कार्य करता है लेकिन समाधान जटिल होने लगता है। क्या कोई बेहतर है?क्लोजरस्क्रिप्ट और ओम के साथ उपयोगकर्ता इनपुट के आधार पर एक सूची को फ़िल्टर कैसे करें?

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

उत्तर

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

मुझे लगता है कि 'सूची-डेटा' केस संवेदी होना चाहिए। '(सूची सूची डेटा [एलीस्ट फ़िल्टर-टेक्स्ट] (फ़िल्टर # (पुनः खोजें (जेएस/रेगेक्स। फ़िल्टर-टेक्स्ट" i ")%) alist)) 'जब आप' '' ' : '(" ज़ेबरा "" बफेलो "" एंटेलोप ") स्रोत: http://stackoverflow.com/questions/23186490/a-case-insensitive-filter-in-clojure-clojurescript?noredirect=1#comment35464719_23186490 – leontalbot

संबंधित मुद्दे