Universal Messaging 10.3 | Developer Guide | Web Client APIs | Web Developer's Guide for Javascript | Web Client Development in JavaScript | Publish/Subscribe Tasks | Subscribing to a Channel
 
Subscribing to a Channel
Once a Universal Messaging Channel object has been created, you can subscribe to the channel, and receive Universal Messaging Events published on the channel.
Simple Subscription
This JavaScript code snippet demonstrates how to subscribe to a channel:

var myChannel = mySession.getChannel("/fxdemo/prices");

function myEventHandler(event) {
var dictionary = event.getDictionary();
console.log(dictionary.get("name") + " " + dictionary.get("bid"));
}

myChannel.on(Nirvana.Observe.DATA, myEventHandler);

myChannel.subscribe();

Note that the subscribe() call is asynchronous; it returns immediately, allowing single-threaded JavaScript clients to continue processing. Whenever an event is received on the channel, however, any user function assigned as a callback for the observable event Nirvana.Observe.DATA will be invoked, with the appropriate Event as its parameter.
Subscription with a Filtering Selector
It is also possible to subscribe to a channel with a user-specified selector (a type of filter), ensuring that your client receives only events that match the selector. Selectors are SQL-like statements such as:
*name LIKE '%bank%' AND description IS NOT NULL
*(vol > 0.5 OR price = 0) AND delta < 1
This JavaScript code snippet demonstrates how to subscribe to a channel and receive only events which have a key named "volatility" and a value greater than 0.5:

var myChannel = mySession.getChannel("/fxdemo/prices");

function myEventHandler(event) {
var dictionary = event.getDictionary();
console.log(dictionary.get("name") + " " + dictionary.get("bid"));
}

myChannel.on(Nirvana.Observe.DATA, myEventHandler);

myChannel.setFilter("name like '%EUR%'");

myChannel.subscribe();
Handling Errors
You may optionally specify an error handler to be notified of subscription or publishing errors:

function myErrorHandler(error) {
console.log(error.message);
}

myChannel.on(Nirvana.Observe.ERROR, myErrorHandler);
If you do not implement an error handler in this way, errors will be silently ignored.