Programming with the widget

The Tradeoff Analytics widget provides a powerful web client that helps users make educated decisions by comparing their options and exploring their tradeoffs. The widget accepts a JSON Problem object that contains the list of options and additional metadata. Its interactive interface then presents an initial panel to get additional information (selected criteria and preferences) from the user.

When the user clicks HELP ME DECIDE, the widget calls the service's dilemmas method, which returns a JSON Dilemma object that contains analytics about the options. The interface presents these results to the user for further exploration. For more information, see Using the visualization interface.

You embed the widget in an application by accessing the TradeoffAnalytics.js script from the Tradeoff Analytics Content Distribution Network (CDN). The script loads the widget inside an iframe and provides an interface for controlling it and for getting notifications from it.

The following sections describe how to integrate and work with the widget in an application. For Node.js sample code to help you get started quickly, see the Tradeoff Analytics Node Starter Application.

Integrating the widget in an application

To integrate the Tradeoff Analytics widget in an application, use the following steps.

Note: The widget calls the Tradeoff Analytics service both to display the initial analysis of a decision problem and when the user modifies the list of active objectives for the problem. In both cases, the application is charged for the call to the service.

  1. Import the client library in your application. The following code includes the library in an HTML file from its public URL.

    <script type="text/javascript" src=""></script>
  2. Create an instance of the widget. The following code calls the constructor for the TradeoffAnalytics object to create a local instance named taClient.

    var taClient = new TradeoffAnalytics(node /* String or DOM node */, options /* Object */);

    The constructor takes two arguments: the required node argument identifies a DOM node from the hosting document in which to place the widget, and the optional options argument specifies the parameters with which to create the instance. For more information, see The TradeoffAnalytics constructor.

  3. Start the widget. The following code creates the iframe and loads the widget inside of it. The widget invokes the optional callback function when it finishes starting and is ready to receive a problem.

    taClient.start(callback /* Function */);
  4. Show the problem. The following code obtains an initial resolution for the problem from the service. You can call the show method multiple times with different data sets. /* Object */, metadata /* Object */);

    The function takes two arguments. The first is the required Problem object; for more information, see Input: Submitting a decision problem. The second is optional metadata that allows you to specify information about the problem for analytical purposes; see Tracking usage for analysis.

  5. Subscribe to event notifications. The following code subscribes to a specified topic with the indicated callback function.

    taClient.subscribe(topic /* String */, callback /* Function */);

    Notifications allow the hosting application to listen for changes to the client state and respond appropriately; see Using event notifications.

  6. Remove subscriptions to event notifications. When you no longer need them, you can remove subscriptions to event notifications for one or all topics by calling the unsubscribe method on the instance of a subscription or by calling the clearSubscriptions or clearAllSubscriptions methods on the instance of the widget; see Using event notifications.

  7. Destroy the instance of the widget. The following code removes the widget's iframe from the containing DOM node and clears all subscriptions.


The TradeoffAnalytics constructor

You call the TradeoffAnalytics constructor to create an instance of the widget for use in your application. The constructor has the following interface:

TradeoffAnalytics(node /* String or DOM node */, options /* Object */)

The required node argument specifies a Document Object Model (DOM) node from the hosting document under which to place the widget's iframe. You can specify a node ID (string) or a DOM element object.

The optional options argument is a JSON object that specifies the parameters with which the instance is to be created. The following table describes the object's fields, all of which are optional.

Table 1. Fields of the options argument
Field Type Default Description
useProxy Boolean false Indicates whether to access the Tradeoff Analytics service through a proxy or directly. If false, uses direct communication via token-based authentication; if true, uses proxy-based communication via service credentials.
dilemmaServiceUrl String Depends on useProxy The URL for the Tradeoff Analytics service, which the widget calls to find the optimal candidate options and to obtain the layout of the map visualization.
  • If useProxy is false, use the address of the service that is accessible via token-based authentication. The default is
  • If useProxy is true, use the address of a proxy server that resides in the same domain as the application and delegates calls to the actual service. The default is /tradeoff-analytics-proxy/dilemmas.
tokenServiceUrl String Depends on useProxy The URL for a server in the same domain as the application that obtains an access token through the Watson token API and returns the token to the client. The client uses the token to communicate directly with the service identified by dilemmaServiceUrl.
  • If useProxy is false, /tradeoff-analytics-token. (For high-level information about using tokens, see Tokens for authentication.)
  • If useProxy is true, the field is ignored.
username String No default The username for accessing the proxy or token service for your application. Specify a username only if you have protected the endpoint for your service with HTTP basic authentication credentials.
password String No default The password for accessing the proxy or token service for your application. Specify a password only if you have protected the endpoint for your service with HTTP basic authentication credentials.
csrfToken String No default A Cross-Site Request Forgery (CSRF) token if you use one to protect your token or proxy endpoints from CSRF attacks. The widget adds the token as an x-csrf-token header that the server can check when it handles the endpoint. For more information, see
themeCssUrl String An absolute URL to a CSS theme for the widget. You can refer to one of the predefined stylesheets or create an application-specific theme and make it available from the web. For more information, see Customizing the widget's appearance.
locale String The browser's locale or en Specifies a language to use with the widget's interface. By default, the widget uses the locale specified by the browser in which the hosting application is running. If the widget does not support the browser's locale, it defaults to using English. Use this argument only if you need to enforce a specific locale.
  • ar (Arabic)
  • de (German)
  • en (English)
  • es (Spanish)
  • fr (French)
  • he (Hebrew)
  • it (Italian)
  • ja (Japanese)
  • ko (Korean)
  • pt (Portuguese)
  • pt-br (Brazilian Portuguese)
  • zh (Chinese)
  • zh-tw (Taiwanese Chinese)
bidiTextDirection String auto The interface direction changes automatically according to the locale. Use this field to specify the text direction to be used:
  • rtl: Right-to-Left, the natural text direction for languages such as Arabic and Hebrew.
  • ltr: Left-to-Right, the natural text direction for languages such as English, German, and French.
  • auto: Contextual text direction, which is the optimal choice when the language of the text is not known in advance.
sendMetadata Boolean true Indicates whether to send metadata with each service call; see Tracking usage for analysis.
metadata Object No default Metadata that provides information about the instance of the TradeoffAnalytics widget; see Tracking usage for analysis.
sendLocationInMetadata Boolean false Indicates whether to send location metadata with each service call. If true, browsers request permission from users to send their location. See Tracking usage for analysis

Using event notifications

The Tradeoff Analytics widget allows the hosting application to be notified when certain events occur, for example, when the user makes a final decision at the end of the decision process. To subscribe to a topic, you call the subscribe method of the TradeoffAnalytics client object. You supply the name of the topic and a callback function; the method returns an object that you can use to unsubscribe from the topic. For a complete list of event notification topics, see Event notification topics.

You can use one of three methods to unsubscribe from topics:

  • The clearSubscriptions method of the TradeoffAnalytics client object takes the name of a topic as its sole argument and removes all subscriptions for the specified topic.
  • The clearAllSubscriptions method of the TradeoffAnalytics client object takes no argument and clears all subscriptions for all topics.
  • The unsubscribe method of a topic object takes no argument and clears the subscription for that specific topic only.

The following example code shows the methods that you can use to subscribe to and to unsubscribe from topics. In the examples, taClient is an instance of the TradeoffAnalytics widget.

function errorHandler(payload){
  // Do something to handle an error. For example, write the error to the console.

// Subscribe to the onError topic with the callback function named errorHandler.
var topic = taClient.subscribe('onError', errorHandler);

// Unsubscribe from the specific onError topic.

// Remove all subscriptions for the onError topic.

// Clear all subscriptions for all topics.

Event notification topics

The following table describes the topics available with the Tradeoff Analytics widget.

Table 2. Available topics
Topic Fires when... Callback parameter type
onError An error occurs due either to invalid input or to a programming error. A string that represents the error message.
problemResolved The service call returns a problem resolution. A JSON Dilemma object that contains the problem and its resolution.
optionClicked The user clicks an option. A JSON Option object that contains the selected option.
compareClicked The user clicks the Compare button in the final phase of the decision process. A list of the JSON Option objects that were selected for detailed comparison.
doneClicked The user clicks the Done button at the end of the decision process. A JSON Option object that contains the option that was selected for the final decision.

Tracking usage for analysis

Knowing how your users are using the Tradeoff Analytics service in your application can provide valuable insights to your business. Such data includes the objectives that users are selecting, the preferences that they are setting for categorical objectives, and so on. With the power of analytics, you can convert this information to novel market insights by answering questions such as

  • What do people look for in a product (common objectives and common preferences for categorical objectives)?
  • Are certain options among the best candidates for all sets of objectives?
  • If your application supports multiple data sets, what data set is used most often?
  • Which users accessed the widget most frequently?

To provide such analytics, the Tradeoff Analytics widget sends metadata in addition to the input problem to the service. The widget and the service generate some metadata automatically; see Metadata generated automatically. As an application developer, you can provide other metadata to the widget; see Metadata provided by the application. You pass metadata to the widget as follows:

  • Via the options parameter of the widget's constructor. Metadata passed via the constructor provides basic information that is appended to the metadata that is automatically generated by the widget and the service.
  • Via the metadata parameter of the widget's show method. Metadata passed via the show method can override or, more commonly, extend the initial data passed to the constructor. In practice, the dataset- fields are most relevant for passing via the show method, though other data can be useful, as well.

In a request to the service, the metadata fields are concatenated in the format key=value and sent via the HTTP header x-watson-metadata. A simple example of metadata follows:

  'app-version': '1.0.0',
  'dataset-id': 'a123'

By default, the widget sends metadata to the service. You can disable metadata by setting the sendMetadata field to false in the options parameter of the widget's constructor.

Metadata generated automatically

The following table describes the built-in metadata that is automatically generated by the widget or the service.

Table 3. Built-in metadata
Field Type Description
service-call-uid String The universally unique identifier (UUID) of the call.
user-agent-uid String A UUID for the user constructed on a best-effort basis by creating and storing a UUID in the widget on the client.
client String The client widget that is used (the current client is called TA_WEB_CLIENT).
client-version String The version of the client widget.
client-locale String The locale used by the client widget.
client-user-agent String The system on which the client runs. In the widget, this is retrieved from navigator.userAgent. In other systems, it may be the type and version of the operating system.
client-ip String The client's IP address, which can be used to learn a coarse geographic location. Since the browser does not know its host IP, this is added on the server-side by the proxy and thus should be implemented by the developer if needed. See the demo applications for examples of its use.
client-location String The client's geographic location (latitude, longitude). This is sent only if the developer enables location acquisition by setting the field sendLocationInMetadata to true. Note that browsers request permission from users to send their location.

Metadata provided by the application

The following table describes metadata that can be provided by the calling application. If your application uses a proxy server to communicate with the service, it can add an ip field; see the demo applications for examples. Your application can also add its own fields to the metadata, but do not include confidential information in any field of the metadata.

Table 4. Application-defined metadata
Field Type Description
app-call-context String A unique identifier for the context in which the call to the service was made (for example, from a particular page in the application). Specify a human-readable identifier that is unique in the scope of the Bluemix organization, space, and application.
app-version String A (sortable) string that identifies the version of the calling application or its context.
dataset-name String A human-readable string that uniquely describes the data set.
dataset-id String A unique identifier for the data set within the organization.
dataset-update-time Number A UNIX timestamp that indicates the last update time of the data set. The timestamp is a count of seconds since the UNIX Epoch of January 1, 1970 Coordinated Universal Time (UTC).
app-session-id String A unique identifier that specifies application-specific session semantics. If the application needs to correlate different instantiations of the widget to a single session, it can pass a session identifier in this field.
app-user-id String A unique, application-specific identifier for the user. Do not include a personal identifier such as the user's real name or username.
app-user-content String If the user is acting on behalf of another person (for example, in the case of a consultant or a doctor), a unique, application-specific identifier for the person being proxied (for example, the customer or patient).

Customizing the widget's appearance

You use themes to control the look and feel of the widget. You specify the theme, or style, for the widget as CSS. Two predefined themes are available for the widget from the Tradeoff Analytics CDN:

You can generate a custom CSS theme file and pass the file to the Tradeoff Analytics widget. You generate a custom stylesheet by using Sass technology (, which supports the use of variables to specify the style. The widget uses a predefined set of variables and default values; for more information about the variables used by the interface, see the file CSS-Theme-Specification.pdf. Note that customization of the visualization is not currently supported; for example, you cannot customize the glyph colors and fonts used in the map visualization.

To generate a custom CSS theme for your application, you must have Node.js and npm installed on your local machine. Once you do, perform the following steps:

  1. Download the zip file that contains the Sass source files for the Tradeoff Analytics service to your local machine from the service's CDN at Extract the contents of the file.

  2. Change to the directory into which you have extracted the contents of the zip file, and run npm install to install the prerequisite software (for example, gulp, the Sass compiler, and so on).

  3. Choose one of the two predefined themes as a starting point. Each theme has a corresponding SCSS file. Copy that file and rename it to something unique, such as myStyle.scss.

  4. Open the file named gulpfile.js in a text editor, and change the themeFileName on line 6 to the name of your custom theme file.

  5. Open your custom theme file in a text editor. The file contains variables for the different colors of the widget. Each variable has a comment that specifies the number that appears in the theme specification document. Edit the colors to suit your design preferences.

  6. To create the CSS file, run gulp compile-theme.

  7. For your convenience, the gulp compiler can regenerate the CSS file each time you save your theme file. To activate this feature, run gulp with no arguments from the command line.

  8. Place the generated CSS file in your web project, and pass its full URL to the TradeoffAnalytics constructor by using the themeCssUrl field of the options parameter; for example:

    taClient = new TradeoffAnalytics('taWidgetContainer',
      { themeCssUrl: '' });

If you do not pass a custom theme or pass an invalid theme, the widget applies the Bright theme by default.