Class: RouterClient

Router Client (Finsemble Workspaces)

For communications amongst desktop services, components, or outside the container entirely, Finsemble provides an event infrastructure with high level protocols. The Router is the center of this functionality, sending and receiving messages between windows.

See the Router tutorial for an overview.

Methods

addListener
(channel, eventHandler)

Adds a listener for incoming transmit events on the specified channel. Each of the incoming events will trigger the specified event handler. The number of listeners is not limited (either local to this Finsemble window or in a separate Finsemble window).

See transmit for sending a corresponding event message to the listener. See removeListener to remove the listener.

Name Type Description
channel string

A unique string to identify the channel (must match corresponding transmit channel name).

eventHandler

A callback handling any possible error and the response. Use response.originatedHere() to determine if the message came from the same window. (see example below).

Example

FSBL.Clients.RouterClient.addListener("SomeChannelName", function (error, response) {
	if (error) {
 		Logger.system.error("ChannelA Error: " + JSON.stringify(error));
	} else {
 		var data response.data;
 		if (response.originatedHere()) {
  			Logger.system.warn("Received a message from the calling window, ignoring");
 		} else {
			// Logic to perform with data
		}
	}
});

addPubSubResponder
(topic, initialState, params, callback)

Adds a PubSub responder for the specified topic (either a specific string or a regular-expression match). PubSub topics are stateful. New subscribers to the topic are automatically provided the most recent state. Once a responder has been added, other apps can subscribe to and publish state on the topic

See `publish()` and `subscribe()`.

Only one responder may be set per topic across the entire system (otherwise a warning will show in Central Logger). If another responder is set with an overlapping regular-expression then the responder with an exact string is still guaranteed to get the messages (the regex responder will not receive messages that match a responder with a matching string).

If multiple responders are set with overlapping regular-expressions, then the receiver is indeterminate.

When initializing a responder, hooks can be provided to intercept and manipulate publish, subscribe, and unsubscribe events (see parameters).

Name Type Description
topic string | RegExp
initialState undefined | object optional

The initial state for the topic (defaults to `{}`).

params undefined | Type Literal optional

Optional hooks

Name Type Description
N/A Type Literal
Name Type Description
publishCallback PublishCallback
subscribeCallback SubscribeCallback
unsubscribeCallback UnsubscribeCallback
callback undefined | Type Literal optional

An optional callback function which should accept a possible error. If `addPubSubResponder()` failed then the first parameter to the callback will contain the error condition. The most common error is when adding a responder for a topic that already has a responder: "RouterClient.addPubSubResponder: Responder already locally defined for topic ${topic}";

Name Type Description
N/A Type Literal
Example

// Example, initializing a responder without any optional hooks:
FSBL.Clients.RouterClient.addPubSubResponder("topicABC", { "State": "start" });

// Example, initializing a responder with a regex for matching topics:
FSBL.Clients.RouterClient.addPubSubResponder(\/topicA*\/, { "State": "start" });

// Example, initializing a responder with all three hooks and an initial state:
FSBL.Clients.RouterClient.addPubSubResponder("topicABC", { "State": "start" },
	{
		subscribeCallback:subscribeCallback,
		publishCallback:publishCallback,
		unsubscribeCallback:unsubscribeCallback
	});

// Example publish hook:
function publishCallback(error, publish) {
	if (publish) {
		// `publish.data` contains the data that the originating app published.
		console.log(publish.data);

		// This function must be called to complete the publication. Set the first parameter to `null`
		// to complete the publication. Set the first parameter to a string in order to suppress the publication
		// and return an error to the publisher.
		//
		// The second parameter must contain the data that you wish to publish. This data will be sent to all
		// subscribers including the originating app. It can be either the originating state (from `publish.data`)
		// or a different/manipulated state. This will become the new current state for the topic.
		publish.sendNotifyToAllSubscribers(null, { someOtherData: "blah"});
	}
}

// Example subscribe hook:
function subscribeCallback(error, subscribe) {
	if (subscribe) {
		// This function must be called to accept or reject the subscription. Send an error code as the first parameter
		// to reject. Send null as the first parameter to accept. Once accepted, the subscriber will receive
		// the current topic's state unless the second parameter is provided which will override what is sent
		// to the subscriber (but not override the topic's actual internal state).
		subscribe.sendNotifyToSubscriber(null, { "NOTIFICATION-STATE": "One" });
	}
}

// Example unsubscribe hook:
function unsubscribeCallback(error, unsubscribe) {
	if (unsubscribe) {
		// This function must be called to accept or reject the unsubscription. Send null (or nothing) as the first
		// parameter to accept the unsubscription. Send an error code to reject it.
		unsubscribe.removeSubscriber(null);
	}
}

addResponder
(channel, queryEventHandler)

Adds a query responder to the specified channel. The responder's queryEventHandler function will receive all incoming queries for the specified channel (whether from this Finsemble window or remote Finsemble windows).

Note: Only one responder is allowed per channel within Finsemble.

See query for sending a corresponding query-event message to this responder.

Name Type Description
channel string

A unique string to identify the channel (must match corresponding query channel name); only one responder is allowed per channel.

queryEventHandler StandardErrorCallback

A function to handle the incoming query (see example below); note the incoming queryMessage contains a function to send the response.

Example

FSBL.Clients.RouterClient.addResponder("ResponderChannelName", function (error, queryMessage) {
	if (error) {
		Logger.system.log('addResponder failed: ' + JSON.stringify(error));
	} else {
		console.log("incoming data=" + queryMessage.data);
		var response="Back at ya"; // Responses can be objects or strings
		queryMessage.sendQueryResponse(null, response); // The callback must respond, else a timeout will occur on the querying client.
	}
});

disconnectAll
()

Removes all listeners, responders, and subscribers for this router client -- automatically called when the client is shutting down. Can be called multiple times.

onReady
(cb)

Checks if Router is ready. May be invoked multiple times. Invokes optional callback and resolves promise when ready, which may be immediately. Router is not ready until underlying transport to Router Service is ready.

Name Type Description
cb undefined | Type Literal optional
Name Type Description
N/A Type Literal

publish
(topic, event)

Publish to a PubSub Responder, which will trigger a corresponding notification to all subscribers (local in this window or remote in other windows). There may be multiple publishers for a topic (again, in same window or remote windows).

See addPubSubResponder for corresponding addition of a PubSub publisher (i.e., sending notifications to all subscriber). See Subscribe for corresponding subscription published results (in the form of a Notify event).

Name Type Description
topic string

A unique string representing the topic being published.

event T

The topic state to be published to all subscribers (unless the PubSub responder optionally modifies in between).

Example

FSBL.Clients.RouterClient.publish("topicABC", topicState);

query
(responderChannel, queryEvent, queryParams, responseEventHandler)

Sends a query to the responder listening on the specified channel. The responder may be in this Finsemble window or another Finsemble window.

See addResponder to add a responder to receive the query.

Name Type Description
responderChannel string

A unique string that identifies the channel (must match the channel name on which a responder is listening).

queryEvent Q

The event message sent to the responder.

queryParams Type Literal | QueryResponseCallback optional
Name Type Description
N/A Type Literal
Name Type Description
logWhenNoResponder
timeout
QueryResponseCallback
responseEventHandler QueryResponseCallback
Example

FSBL.Clients.RouterClient.query("someChannelName", {}, function (error, queryResponseMessage) {
	if (error) {
		Logger.system.log('query failed: ' + JSON.stringify(error));
	} else {
		// process income query response message
		var responseData = queryResponseMessage.data;
		Logger.system.log('query response: ' + JSON.stringify(queryResponseMessage));
	}
});

FSBL.Clients.RouterClient.query("someChannelName", { queryKey: "abc123"}, { timeout: 1000 }, function (error, queryResponseMessage) {
	if (!error) {
		// process income query response message
		var responseData = queryResponseMessage.data;
	}
});

removeListener
(channel, eventHandler)

Removes an event listener from the specified channel for the specific event handler; only listeners created locally can be removed.

See addListener for corresponding add of a listener.

Name Type Description
channel string

The unique channel name from which to remove the listener.

eventHandler Function

Function used for the event handler when the listener was added.

removePubSubResponder
(topic)

Removes a PubSub responder from the specified topic. Only locally created responders (i.e. created in the local window) can be removed.

See addPubSubResponder for corresponding addition of a PubSub responder.

Name Type Description
topic string | RegExp

Unique topic for responder being removed (may be RegEx, but if so much be exact RegEx used previously with addPubSubResponder).

Example

FSBL.Clients.RouterClient.removePubSubResponder("topicABC");

removeResponder
(responderChannel)

Removes the query responder from the specified channel. Only a locally added responder can be removed (i.e., a responder defined in the same component or service).

See addResponder for adding a query responder.

Name Type Description
responderChannel string

String identifying the channel from which to remove the responder.

Example

FSBL.Clients.RouterClient.removeResponder("someChannelName");

subscribe
(topic, notifyCallback)

Subscribe to a PubSub responder. Each responder topic can have many subscribers (local in this window or remote in other windows). Each subscriber immediately (but asynchronously) receives back current state in a notify; new notifications are received for each publish sent to the same topic.

See addPubSubResponder for corresponding addition of a PubSub responder to handle the subscribe. See publish for how to publish data to subscribers.

Name Type Description
topic string

A unique string representing the topic being subscribed to.

notifyCallback

Invoked on immediately upon subscription, then again on each incoming notification for the specified topic.

Example

var subscribeId = RouterClient.subscribe("topicABC", function(err, notify) {
	if (!err) {
		var notificationStateData = notify.data;
		// do something with notify data
	}
});


transmit
(toChannel, data, options)

Transmits data to all listeners on the specified channel. If there are no listeners on the channel, the event is discarded without error. All listeners on the channel in this Finsemble window and other Finsemble windows will receive the transmit.

See addListener to add a listener to receive the transmit.

Name Type Description
toChannel string

A unique string to identify the channel (must match corresponding listener channel name).

data T

An object or primitive type to be transmitted.

options undefined | Type Literal optional

An object containing options for your transmission.

Name Type Description
N/A Type Literal
Name Type Description
suppressWarnings boolean
Example

FSBL.Clients.RouterClient.transmit("SomeChannelName", event);

trustedMessage
(incomingMessage)

Tests an incoming Router message to see if it originated from the same origin (i.e., a trusted source; not cross-domain).

Currently, the origin of an incoming Router message is determined by way of the SharedWorker transport. By definition, SharedWorkers do not work across domains. This means any message coming in over the transport will not be trusted. However, by default, all same-origin components and services connect to the Router using a SharedWorker transport.

Name Type Description
incomingMessage RouterMessage
Name Type Description
data T
header RouterHeader
options
Name Type Description
supressWarnings boolean
originatedHere
Example
FSBL.Clients.RouterClient.trustedMessage(incomingRouterMessage);

unsubscribe
(subscribeIDStruct)

Unsubscribes from a PubSub responder so no more notifications are received (but doesn't affect other subscriptions). Only works from the window the PubSub responder was created in.

See subscribe for corresponding subscription being removed.

Name Type Description
subscribeIDStruct
Name Type Description
subscribeID string
topic string
Example

FSBL.Clients.RouterClient.unsubscribe(subscribeId);