Nirvana JavaScript Sandbox

The Nirvana JavaScript Sandbox is an interactive tutorial to quickly familiarise you with the Nirvana JavaScript API. The sandbox allows you to edit and run example JavaScript code in your browser, without needing to install a Nirvana Realm server.

Sandbox Examples

    Notes

    The sandbox contains a few predefined functions which may be of use when experimenting:

    • log(msg)
    • error(msg)

    You can double-click the sandbox code area to edit the example code, and click the Run button to execute your code.

    Ready? Try it out on the first example, which will show you how to set up a Nirvana session.

    NirvanaSession : Getting Started
    // The NirvanaSession object is pre-instantiated (though not started)
    // for you when your application includes nirvana.js. 
    
    // First, specify what should happen when a session successfully starts.
    // For now, we'll just use the sandbox utility functions log() and error():
    
    NirvanaSession.onInit = function(sessionid) { 
    	log("Session Initialised with ID " + sessionid); 
    };
    
    NirvanaSession.onReconnect = function() { 
    	log("Session Reconnected.");
    };                              
    
    // Then, start the session:
    
    NirvanaSession.start({
    	domain	  : "my-channels.com",  // as we are going to use realm showcase.my-channels.com
    	realmHosts      : [ "showcase" ],	   // an array of realm hostnames - in this case just the one 
    	applicationName : "sandbox",	  // tell the server our app name
    	sessionName     : "sandboxSession",   //  ... and our chosen sessionName
    	username	: "sandboxUser"       //  ... and a personal identifier
    });
    
    // Note that if you deployed your application to your own Nirvana Realm server, 
    // you probably wouldn't need to use the domain and realmHosts configuration options.
    
    Channels : Subscribing
    NirvanaSession.onInit = function(sessionid) { 
    
    	// Specify what should happen when a session successfully starts:
    
    	var chan = new NirvanaChannel("/tutorial/sandbox");
    
    	// Define what happens when our channel subscription is successful:
    
    	chan.onSubscribe = function(channelName) {
    		log("Subscribed to " + channelName); 
    	};
    
    	// ... and what happens when the subscribed channel receives an event:
    
    	chan.onData = function(event) {
    		log("Received event " + event.getEID() + " from " + event.getChannelName());
    	};
    
    	// We're now ready to kick off the channel subscription:
    
    	chan.subscribe();
    
    };
    
    NirvanaSession.start({
    	domain	  : "my-channels.com",
    	realmHosts      : [ "showcase" ],
    	applicationName : "sandbox",
    	sessionName     : "sandboxSession",
    	username	: "sandboxUser"
    });
    
    Channels : Publishing
    NirvanaSession.onInit = function(sessionid) {
    
    	var chan = new NirvanaChannel("/tutorial/sandbox");
    
    	// Define what happens when our publish attempt is complete:
    
    	chan.onPublish = function(status) { 
    		log("Publish to " + this.name + " : " + status);
    	};
    
    	// Let's prepare an event for publishing.
    	// In this example, we'll add a dictionary to our event, with a key named "message":
    
    	var dict = new nEventProperties();
    	dict.put("message", "Hello World");
    
    	var evt = new nConsumeEvent();
    	evt.setDictionary(dict);
    
    	// Publish our event:
    
    	chan.publish(evt);
    
    };
    
    NirvanaSession.start({
    	domain	  : "my-channels.com",
    	realmHosts      : [ "showcase" ],
    	applicationName : "sandbox",
    	sessionName     : "sandboxSession",
    	username	: "sandboxUser"
    });
    
    Channels : Publishing and Subscribing
    NirvanaSession.onInit = function(sessionid) {
    
    	var chan = new NirvanaChannel("/tutorial/sandbox");
    
    	chan.onSubscribe = function(channelName) {
    	
    		// As soon as we've successfully subscribed, we shall publish a message.
    		// Note that we don't have to subscribe in order to publish, but if we want
    		// to *receive* the event we've published, we do of course need to subscribe.
    
    		log("Subscribed to " + channelName);
    		var dict = new nEventProperties();
    		dict.put("message", "Hello World");
    		var evt = new nConsumeEvent();
    		evt.setDictionary(dict);
    		this.publish(evt);
    	};
    
    	// Note that when publishing to a channel to which you are subscribed,
    	// the onPublish callback my fire before the onData callback, or vice-versa;
    	// the two callbacks are fired asynchronously, and there is no guarantee
    	// of order. Try running this example several times to see.
    
    	chan.onPublish = function(status) {
    		log("Publish to " + this.name + " : " + status);
    	};
    
    	chan.onData = function(event) {
    		try {   
    			log("Received event " + event.getEID() + " from " + event.getChannelName());
    			log("Message is: " + event.getDictionary().get("message"));
    		} catch(e) {
    			error(e.message);
    		}  
    	};
    
    	chan.subscribe();
    
    };
    
    NirvanaSession.start({
    	domain	  : "my-channels.com",
    	realmHosts      : [ "showcase" ],
    	applicationName : "sandbox",
    	sessionName     : "sandboxSession",
    	username	: "sandboxUser"
    });
    
    Channels : Subscription Filters and Other Options
    NirvanaSession.onInit = function(sessionid) {
    
    	var chan = new NirvanaChannel("/tutorial/sandbox");
    
    	chan.onSubscribe = function(channelName) {
    		publishExampleEvents(this);
    	};
    
    	chan.onPublish = function(status) {
    		log("Publish to " + this.name + " : " + status);
    	};
    
    	chan.onData = function(event) {
    		try {   
    			var dict = event.getDictionary();
    			log(dict.get("name") + " price is " + dict.get("price"));
    		} catch(e) {
    			error(e.message);
    		}  
    	};
    
    	// The channel subscribe call accepts an optional configuration parameter.
    	// Here we can specify an optional event ID from which to subscribe,
    	// ... and/or a dictionary key filter to only receive matching events:
    	
    	chan.subscribe({
    		startEID : 1,
    		filter : "name LIKE 'GOLD%' AND price > 500"
    	});
    
    };
    
    NirvanaSession.start({
    	domain	  : "my-channels.com",
    	realmHosts      : [ "showcase" ],
    	applicationName : "sandbox",
    	sessionName     : "sandboxSession",
    	username	: "sandboxUser"
    });
    
    function publishExampleEvents(channel) { 
    	for (var i=1; i < 4; i++) { 
    		var dict = new nEventProperties();
    		dict.put("name", "GOLD" + i);
    		dict.putInteger("price", (i+4) * 100);
    		var evt = new nConsumeEvent();
    		evt.setDictionary(dict);
    		channel.publish(evt);
    	}
    }
    
    Channels : More Callbacks and Methods
    NirvanaSession.onInit = function(sessionid) {
    
    	var chan = new NirvanaChannel("/tutorial/sandbox");
    
    	chan.onSubscribe = function(channelName) { log("Subscribed to " + channelName); };
    	chan.onUnsubscribe = function(channelName) { log("Unsubscribed from " + channelName); };
    	chan.onPublish = function(status) { log("Publish to " + this.name + " : " + status); };
    	chan.onData = function(event) { log("Received event " + event.getEID() + " from " + event.getChannelName()); };
    	chan.onError = function(err) { error(err.name + " : " + err.message + " [" + this.name + "]"); };
    
    	chan.subscribe();
    	chan.publish(); // <= this is invalid, so will invoke an onError callback 
    	chan.publish(new nConsumeEvent());
    	chan.unsubscribe();
    
    };
    
    NirvanaSession.start({
    	domain	  : "my-channels.com",
    	realmHosts      : [ "showcase" ],
    	applicationName : "sandbox",
    	sessionName     : "sandboxSession",
    	username	: "sandboxUser"
    });
    
    P2P : Connecting, Writing and Receiving Events
    // A Nirvana Realm can transparently broker messages between an instance of a service and a client
    // requiring access to the service. This example implementes a P2P client which uses the realm to
    // communicate with a simple demo backend "echo" service that is running and connected to the server:
    
    NirvanaSession.onInit = function(sessionid) {
    
    	log("Session Initialised with ID " + sessionid); 
    	
    	var	echoService = new NirvanaService("echo");
    
    	echoService.onConnect = function() { log("Connected to " + this.name + " service"); }
    	echoService.onReconnect = function(name, state) { log("Reconnected to " + name + " service. Its state is " + state); }
    	echoService.onWrite = function() { log("Successfully sent message to the echo service"); }
    	echoService.onData = function(event) { log("Received event from " + event.cname); }
    	echoService.onError = function(err) { error(err.name + " : " + err.message + " [" + this.name + "]"); };
    
    	log("Connecting to the echo service..."); 
    	echoService.connect();
    
    	// write a test event to the service:
    	
    	var dict = new nEventProperties();
    	dict.put("somemessage", "Hello World at " + new Date());
    	var evt = new nConsumeEvent();
    	evt.setDictionary(dict);
    	
    	echoService.write(evt);
    
    };
    
    NirvanaSession.start({
    	domain	  : "my-channels.com",
    	realmHosts      : [ "showcase" ],
    	applicationName : "sandbox",
    	sessionName     : "sandboxSession",
    	username	: "sandboxUser"
    });
    
    NirvanaSession : More Callbacks
    // The NirvanaSession object has several callbacks for which you can implement logic:
    
    NirvanaSession.onInit = function(sessionid) { 
    	log("Session Initialised with ID " + sessionid); 
    };
    
    NirvanaSession.onDisconnect = function() {
    	log("Session Disconnected. Reconnecting...");
    }
    
    NirvanaSession.onReconnect = function() { 
    	log("Session Reconnected.");
    }
    
    NirvanaSession.onReset = function() {
    	log("Session was reset by server.");
    }
    
    NirvanaSession.onData = function(event) {
    	log("Received a DataStream event from " + event.getDataGroupName());
    }
    
    NirvanaSession.onError = function(err) {
    	error(err.name + " : " + err.message);
    }
    
    
    NirvanaSession.start({
    	domain	    : "my-channels.com",  // as we are going to use realm showcase.my-channels.com
    	realmHosts	: [ "showcase" ],	   // an array of realm hostnames - in this case just the one 
    	applicationName   : "sandbox",	  // tell the server our app name
    	sessionName       : "sandboxSession",   //  ... and our chosen sessionName
    	username	  : "sandboxUser",      //  ... and a personal identifier
    	enableDataStreams : true
    });
    
    NirvanaSession : WebSocket, Streaming Comet or Long Polling Comet?
    // By default, Nirvana will connect using Streaming Comet. You can override this with
    // the optional configuration parameters webSocket and longPoll to true or false:
    
    NirvanaSession.onInit = function(sessionid) { 
    	log("Session Initialised with ID " + sessionid); 
    };
    
    NirvanaSession.onReconnect = function() { 
    	log("Session Reconnected.");
    };
    
    // Then, start the session:
    
    NirvanaSession.start({
    	domain	  : "my-channels.com",  // as we are going to use realm showcase.my-channels.com
    	realmHosts      : [ "showcase" ],	   // an array of realm hostnames - in this case just the one 
    	applicationName : "sandbox",	  // tell the server our app name
    	sessionName     : "sandboxSession",   //  ... and our chosen sessionName
    	username	: "sandboxUser",       //  ... and a personal identifier
    	webSocket	: true,	// will use WebSocket if supported by browser, or Comet if not
    	longPoll	: true	// if using Comet, will Long Poll instead of Stream
    });