Realtime REST demo

Realtime improves user experience (UX) and the speed of communication. RestDB.io lets your application subscribe to Data Events in realtime. This example shows a chat application that visualises REST Data Events (PUT, POST, DELETE) and the executing code block. To get started, create a new database, read the docs and look at the Github code example.

Send a link to this page to your team/friends, start chatting, and watch the events propagate.

Chat


Double click or swipe right to delete

The code


// Called when new records are inserted into the database
        db.chat.on('POST', function(err, mess) {
        	var line = $("<div>").text(mess.data.oneliner + " " + mess.data._id);
        	line.hide();
        	$("#messages").prepend(line);
        	line.toggle("scale")
        });
        
// Called when a record is changed in the database
        db.chat.on('PUT', function(err, mess) {
        	db.chat.find({"_id": mess.data}, {}, function(err, updatedline){
        	    $("#"+mess.data).text(updatedline[0].oneliner);
        	});
        });
        
// Called when one or more record is deleted in the database
        db.chat.on('DELETE', function(err, mess) {
            _.each(mess.data, function(oneid){
                $("#"+oneid).remove();    
            });
        });
        
// The initial setup and connection the a realtime database
        var apikey = "577ed0a645c8ac6e5b035fbe";
        var db = null; 
        try {
            db = new restdb(apikey, {realtime: true});
            $("#status").text("Ok, got the api").addClass("online");
        } catch (ex) {
            $("#status").text("Error loading jsapi");
        }
        
// Called when a user types something in the input field
        $("#oneliner").keyup(function(e){
        	if(e.keyCode == 13)
        	{
        		var payload = {"oneliner": $(this).val()};
        		$(this).val("");
        		var newline = new db.chat(payload);
        		newline.save();
        	}
        });
        
// Called when a connection is established
        db.on("CONNECT", function() {
        	$("#status").addClass("online").removeClass("offline").text("online");
        	$("#messages").empty();
        	db.chat.find({}, {"$max": 100,"$orderby": {"_created": -1}}, function(err, lines){
        	    _.each(lines, function(aline){
        	        $("#messages").append($("<div>").text(aline.oneliner));        
        	    });
        	})
        });
        
//Called when the connection is lost, unplug your wifi to see this
        db.on("DISCONNECT", function() {
        	console.log("Realtime closed: ");
        	$("#status").addClass("online").addClass("offline").text("off");
        });
        
// Called after a lost connection is regained
        db.on("RECONNECT", function() {
        	$("#status").addClass("online").removeClass("offline").text("Back again");
        });
        
View Source