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
transmitfor sending a corresponding event message to the listener. SeeremoveListenerto remove the listener.Name Type Description channelstring A unique string to identify the channel (must match corresponding transmit channel name).
eventHandlerA 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 topicstring | RegExp initialStateundefined | object optional The initial state for the topic (defaults to `{}`).
paramsundefined | Type Literal optional Optional hooks
Name Type Description N/AType Literal Name Type Description publishCallbackPublishCallback subscribeCallbackSubscribeCallback unsubscribeCallbackUnsubscribeCallback callbackundefined | 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/AType 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
queryEventHandlerfunction 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
queryfor sending a corresponding query-event message to this responder.Name Type Description channelstring A unique string to identify the channel (must match corresponding query channel name); only one responder is allowed per channel.
queryEventHandlerStandardErrorCallback A function to handle the incoming query (see example below); note the incoming
queryMessagecontains 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 cbundefined | Type Literal optional Name Type Description N/AType 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
addPubSubResponderfor corresponding addition of a PubSub publisher (i.e., sending notifications to all subscriber). SeeSubscribefor corresponding subscription published results (in the form of aNotifyevent).Name Type Description topicstring A unique string representing the topic being published.
eventT 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
addResponderto add a responder to receive the query.Name Type Description responderChannelstring A unique string that identifies the channel (must match the channel name on which a responder is listening).
queryEventQ The event message sent to the responder.
queryParamsType Literal | QueryResponseCallback optional Name Type Description N/AType Literal Name Type Description logWhenNoRespondertimeoutQueryResponseCallbackresponseEventHandlerQueryResponseCallback 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
addListenerfor corresponding add of a listener.Name Type Description channelstring The unique channel name from which to remove the listener.
eventHandlerFunction 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
addPubSubResponderfor corresponding addition of a PubSub responder.Name Type Description topicstring | 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
addResponderfor adding a query responder.Name Type Description responderChannelstring 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
addPubSubResponderfor corresponding addition of a PubSub responder to handle the subscribe. Seepublishfor how to publish data to subscribers.Name Type Description topicstring A unique string representing the topic being subscribed to.
notifyCallbackInvoked 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
addListenerto add a listener to receive the transmit.Name Type Description toChannelstring A unique string to identify the channel (must match corresponding listener channel name).
dataT An object or primitive type to be transmitted.
optionsundefined | Type Literal optional An object containing options for your transmission.
Name Type Description N/AType Literal Name Type Description suppressWarningsboolean 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 incomingMessageRouterMessage Name Type Description dataT headerRouterHeader optionsName Type Description supressWarningsboolean originatedHereExample
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
subscribefor corresponding subscription being removed.Name Type Description subscribeIDStructName Type Description subscribeIDstring topicstring Example
FSBL.Clients.RouterClient.unsubscribe(subscribeId);