Watcher是添加到變量類型的函數(shù),例如atom和引用變量,當(dāng)變量類型的值改變時(shí)調(diào)用。 例如,如果調(diào)用程序更改atom變量的值,并且如果Watcher函數(shù)附加到atom變量,則一旦atom的值改變,該函數(shù)將被調(diào)用。
Clojure for Watchers中提供了以下功能。
向agent / atom / var / ref引用添加watch函數(shù)。 手表'fn'必須是4個(gè)參數(shù)的'fn':一個(gè)鍵,引用,它的舊狀態(tài),它的新狀態(tài)。 每當(dāng)引用的狀態(tài)可能已更改,任何注冊的手表都將調(diào)用其函數(shù)。
以下是 Watcher 基本使用語法:
(add-watch variable :watcher (fn [key variable-type old-state new-state]))
參數(shù) - 'variable'是原子或引用變量的名稱。 'variable-type'是變量的類型,原子或引用變量。 '舊狀態(tài)和新狀態(tài)'是將自動(dòng)保存變量的舊值和新值的參數(shù)。 'key'對于每個(gè)引用必須是唯一的,并且可以用于刪除帶有remove-watch的手表。
返回值 -無。
下面是一個(gè) Watcher 使用的例子。
(ns clojure.examples.example (:gen-class)) (defn Example [] (def x (atom 0)) (add-watch x :watcher (fn [key atom old-state new-state] (println "The value of the atom has been changed") (println "old-state" old-state) (println "new-state" new-state))) (reset! x 2)) (Example)
以上示例輸出以下結(jié)果:
The value of the atom has been changed old-state 0 new-state 2
除去已附著在引用變量的手表。
以下是 移除Watcher 基本使用語法:
(remove-watch variable watchname)
參數(shù) - 'variable'是atom或引用變量的名稱。 'watchname'是定義監(jiān)視功能時(shí)給Watcher 的名稱。
返回值 -無。
(ns clojure.examples.example (:gen-class)) (defn Example [] (def x (atom 0)) (add-watch x :watcher (fn [key atom old-state new-state] (println "The value of the atom has been changed") (println "old-state" old-state) (println "new-state" new-state))) (reset! x 2) (remove-watch x :watcher) (reset! x 4)) (Example)
以上示例輸出以下結(jié)果:
The value of the atom has been changed old-state 0 new-state 2
從上面的程序可以清楚地看到,第二個(gè)重置命令不會觸發(fā)觀察者,因?yàn)樗粡挠^察者的列表中刪除。
更多建議: