Diffusion Cloud 6.3.0 User Manual

Start subscribing with JavaScript

Create a JavaScript® browser client within minutes that
connects to Diffusion™ Cloud. This example creates a web page that
automatically updates and displays the value of a topic.

To complete this example, you need a Diffusion Cloud
service and a web server where you can host your client application. For more information
about getting a Diffusion Cloud service, see Getting started with Diffusion Cloud.

You also require either a named user that has a role with the select_topic and read_topic permissions or that anonymous client connections are assigned a role
with the select_topic and read_topic permissions. For example, the "CLIENT"
role. For more information about roles and permissions, see Role-based authorization.

This example steps through the lines of code required to subscribe to a topic. There are several different
topic types which provide data in
different formats. This example shows you how to subscribe to a JSON topic. The
full code example is provided after the
steps.

The subscribe() method of the session object
takes the name of the topic to subscribe to and emits an update event. The attached
function takes the data from the topic and updates the update element
of the web page with the topic data.

Change the function that is called on connection to the
subscribeToJsonTopic function you just created.

.then(subscribeToJsonTopic);

If you open the page in a web browser it looks like the following screenshot:

The web page is updated every time the value of the foo/counter topic is updated. You can update the value of the foo/counter topic by using
the Diffusion Cloud Dashboard's test client or by creating a
publishing client to update the topic. To create and publish to the foo/counter topic, you require a user with the modify_topic and update_topic permissions. For more information, see Start publishing with JavaScript.