Nirvana JavaScript : Subscribing to a NirvanaChannel

Once a Nirvana Channel object (NirvanaChannel) has been created, you can subscribe to the channel, and receive Nirvana Events published on the channel.

Simple Subscription

This JavaScript code snippet demonstrates how to subscribe to a channel:

var demoChannel = new NirvanaChannel("/some/demo/channel");

demoChannel.onData = function(event) {
	// define what we do when we receive an event
}

demoChannel.subscribe();

Note that the demoChannel.subscribe() call is asynchronous; it returns immediately, allowing single-threaded JavaScript clients to continue processing. Whenever an event is received on the NirvanaChannel, however, the demoChannel.onData function is invoked, with the 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 demoChannel = new NirvanaChannel("/some/demo/channel");

demoChannel.onData = function(event) {
	// define what we do when we receive an event
}

demoChannel.subscribe({
	filter : "volatility > 0.5"
});

Again, note that the demoChannel.subscribe() call is asynchronous; it returns immediately, allowing single-threaded JavaScript clients to continue processing. As soon as an event is received on the NirvanaChannel, the demoChannel.onData function is invoked, with the event as a parameter.

Handling Received Events

As discussed above, you should implement a function to handle any received events. In our examples above, the callback function demoChannel.onData has been assigned to an anonymous function:

demoChannel.onData = function(event) {
	// define what we do when we receive an event
}

You may, if you prefer, assign some other named function to handle events as follows:

demoChannel.onData = demoHandler;

function demoHandler(event) {
	// define what we do when we receive an event
}

Using a named function is particularly useful if you wish to use the same handler for events from several different channels.

Handling Errors

You may optionally specify an error handler to be notified of subscription or publishing errors:

demoChannel.onError = function(errorMessage) {
        // define what we do when we receive the errorMessage
}

If you do not implement an error handler in this way, errors will be silently ignored.