## Tracker
Meteor 包含一個簡單地依賴跟蹤系統,使用它可以在[`Session`](#session)變量、數據庫查詢或其它數據源發生變化時自動重新渲染模板或是重新運行某些函數。
和其它的依賴跟蹤系統不同,不需要手工聲明依賴— 它就能工作。它的機制簡單而高效。一旦你用`Tracker.autorun`初始化了一個計算(computation), `Tracker` 自動記錄使用到的數據。當這些數據發生變化時,計算就會自動重新運行。這就是為什么當[helper functions](#template_helpers)返回新數據時模板知道如何重新渲染。
### [Tracker.autorun(runFunc, [options])](#/basic/Tracker-autorun)
Client
Run a function now and rerun it later whenever its dependencies change. Returns a Computation object that can be used to stop or observe the rerunning.
#### Arguments
runFunc Function
The function to run. It receives one argument: the Computation object that will be returned.
#### Options
onError Function
Optional. The function to run when an error happens in the Computation. The only argument it recieves is the Error thrown. Defaults to the error being logged to the console.
`Tracker.autorun`使你可以聲明一個依賴響應式數據源的函數,無論何時數據源發生變化,函數都會被重新執行。
例如,可以監測一個`Session`變量,設置另外一個:
```
Tracker.autorun(function () {
var celsius = Session.get("celsius");
Session.set("fahrenheit", celsius * 9/5 + 32);
});
```
或者可以等待session變量成為一個特定值,執行一些特定操作。如果想阻止回調函數進一步重新運行,可以調用計算(computation)對象的`stop`,計算對象會作為回調函數的第一個參數傳入:
```
// Initialize a session variable called "counter" to 0
Session.set("counter", 0);
// The autorun function runs but does not alert (counter: 0)
Tracker.autorun(function (computation) {
if (Session.get("counter") === 2) {
computation.stop();
alert("counter reached two");
}
});
// The autorun function runs but does not alert (counter: 1)
Session.set("counter", Session.get("counter") + 1);
// The autorun function runs and alerts "counter reached two"
Session.set("counter", Session.get("counter") + 1);
// The autorun function no longer runs (counter: 3)
Session.set("counter", Session.get("counter") + 1);
```
`Tracker.autorun`第一次被調用的時候,回調函數立即被執行,如果此時`counter === 2`,那么就會alert,然后立即停止。在上面的例子中,當`Tracker.autorun`被調用時,`Session.get("counter") === 0`,所以第一次什么都不會發生,每次`counter`發生變化時,回調函數都會重新運行,直到當`counter` 等于`2`的時候,`computation.stop()`被調用。
如果autorun在第一次執行時拋出了異常,那么計算(computation)會自動停止,以后也不會重新運行。
關于`Tracker`的工作原理和高級用法,參見[Meteor 手冊](http://manual.meteor.com/)里的[Tracker](http://manual.meteor.com/#tracker)一節,里面有更加詳細的說明。