# Event

Packhouse提供了簡單的事件系統，主要提供於追蹤呼叫行為。

{% hint style="info" %}
除非特殊情況，你不需要自己處理事件追蹤，使用[Step](https://packhouse-doc.metalsheep.com/plugins/step)，可以輕鬆追蹤整個運行過程。
{% endhint %}

## Add Listener

#### Use

第一次使用Tool時觸發：

{% hint style="info" %}
嚴格來說Line是一連串的Tool執行，在呼叫Line的事件中你會發現Name會以Namespace的模式顯示。
{% endhint %}

```javascript
packhouse.on('use', (event, { type, name, group }) => {
    console.log(type) // tool
    console.log(name) // sum
    console.log(group.sign) // null *this is merger sign
    console.log(group.name) // math
})

packhouse.tool('math/sum').action(...)
```

#### Run

每次執行Tool時會被觸發：

```javascript
packhouse.on('run', (event, { id, caller, detail }) => {
    let { name, args, mode, request, response, group } = detail
    console.log(id) // uuid, 每次執行都會配發一個新的id
    console.log(caller) // 如果該次呼叫是由另一個tool調用，可以得知是哪個id呼叫
    console.log(name) // sum
    console.log(args) // [10, 20]
    console.log(mode) // action
    console.log(request) // "[\"number\", \"number\"]"
    console.log(response) // number
    console.log(group.sign) // null *this is merger sign
    console.log(group.name) // math
})

packhouse.tool('math/sum').action(10, 20, () => {})
```

### Done

運行結束時觸發：

```javascript
packhouse.on('done', (event, { id, caller, detail }) => {
    let { result, success } = detail
    console.log(id) // 與執行的id相同
    console.log(caller) // 如果該次呼叫是由另一個tool調用，可以得知是哪個id呼叫
    console.log(success) // true
    console.log(result) // 30
})

packhouse.tool('math/sum').action(10, 20, () => {})
```

## Remove Listener

每次監聽事件都會回傳一個監聽Id，因此可以藉由該Id指定移除事件：

```javascript
let id = packhouse.on('run', () => {})

packhouse.off('run', id)
```

也可以利用第一個`event`參數來關閉事件：

```javascript
packhouse.on('run', event => event.off())
```
