目录

Clojure - Watchers(Watchers)

Watchers是添加到变量类型的函数,例如原子和引用变量,当变量类型的值发生变化时,它们会被调用。 例如,如果调用程序更改了atom变量的值,并且如果将watcher函数附加到atom变量,则只要原子的值发生更改,就会调用该函数。

Clojure for Watchers提供以下功能。

add-watch

向watch/atom/var/ref引用添加监视功能。 手表'fn'必须是4个参数的'fn':一个键,一个参考,它的旧状态,它的新状态。 每当参考的状态可能已被更改时,任何已注册的手表都将调用其功能。

语法 (Syntax)

以下是语法。

(add-watch variable :watcher
   (fn [key variable-type old-state new-state]))

Parameters - 'variable'是原子或引用变量的名称。 'variable-type'是变量的类型,原子或引用变量。 'old-state&new-state'是将自动保存变量的旧值和新值的参数。 'key'必须是每个参考的唯一,并可用于删除手表与删除手表。

Return Value - 无。

例子 (Example)

以下程序显示了如何使用它的示例。

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

输出 (Output)

上述程序产生以下输出。

The value of the atom has been changed
old-state 0
new-state 2

remove-watch

移除已附加到参考变量的手表。

语法 (Syntax)

以下是语法。

(remove-watch variable watchname)

Parameters - 'variable'是原子或引用变量的名称。 'watchname'是定义手表功能时给手表的名称。

Return Value - 无。

例子 (Example)

以下程序显示了如何使用它的示例。

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

输出 (Output)

上述程序产生以下输出。

The value of the atom has been changed
old-state 0
new-state 2

您可以从上面的程序中清楚地看到,第二个重置命令不会触发观察者,因为它已从观察者列表中删除。

↑回到顶部↑
WIKI教程 @2018