# Guides

## Safely adds events in `window.iAdvizeCallbacks` object <a href="#safely-adds-events-in-window.iadvizecallbacks-object" id="safely-adds-events-in-window.iadvizecallbacks-object"></a>

If you need to add iAdvize callbacks in different places in your code, you should always declare your callbacks like the following example to avoid overwriting a previous callback definition:

```javascript
window.iAdvizeCallbacks = {
  ...window.iAdvizeCallbacks,
  
  onChatStarted() {
    // Do something
  },
  
  onChatEnded() {
    // Do something
  }
  
};

// Later in your code:
window.iAdvizeCallbacks = {
  ...window.iAdvizeCallbacks,
  
  onMessageReceived(context) {
    // Do something
  }
  
};
```

With this approach, iAdvize will see 3 callbacks: `onChatStarted`, `onChatEnded` et `onMessageReceived`.

## Safely define a function for an event <a href="#safely-define-a-function-for-an-event" id="safely-define-a-function-for-an-event"></a>

If your code is splitted in multiple files or module, you may need to define several functions for the same event.

Here is a solution to avoid overwriting a previous function:

```javascript
var tempOnChatStarted = window.iAdvizeCallbacks.onChatStarted || () => {};

window.iAdvizeCallbacks = {
  ...window.iAdvizeCallbacks,
  
  onChatStarted(context) {

    // Call the possible already defined callback
    tempOnChatStarted(context);

    // Your new custom code here
    // ...
    
  }
  
};
```

## Track some Google Analytics events <a href="#track-some-google-analytics-events" id="track-some-google-analytics-events"></a>

```javascript
window.iAdvizeCallbacks = {

  ...window.iAdvizeCallbacks,
  
  // Chat conversation starts
  onChatStarted(context) {
    _gaq.push(['_trackEvent', 'iAdvize', 'Chat Start', context.startedBy]);
  },
  
  // Chat conversation ends
  onChatEnded(context) {
    _gaq.push(['_trackEvent', 'iAdvize', 'Chat End', context.startedBy]);
  },
  
  // Call conversation starts
  onCallStarted() {
    _gaq.push(['_trackEvent', 'iAdvize', 'Call Start']);
  },
  
  // Call conversation ends
  onCallEnded() {
    _gaq.push(['_trackEvent', 'iAdvize', 'Call End']);
  }

};
```
