Skip to content

Getting up and running with long polling

andrerpena edited this page Sep 20, 2013 · 33 revisions

Long polling is a good tecnique for sending live data from the server to the client. However, it may get a little tricky when you have multiple data formats. For instance, ChatJS has three different data formats: One for when the users list change, another for new messages, and a last one for when the other using is typing. How do you make sure that the proper client function is going to be called for that particular data format when it arrives in the client?

To solve the above problem, ChatJS defines two function: $.addLongPollingListener() and $.startLongPolling(). The first one will define that, for a given data-format, the passed in function must be called.

Example

$.addLongPollingListener("chat",
	// success
	function (event) {
		if (event.EventKey == "new-messages")
			for (var i = 0; i < event.Data.length; i++)
				chat.client.sendMessage(event.Data[i]);
		else if (event.EventKey == "user-list")
			chat.client.usersListChanged(event.Data);
		// other checks
	},
	// error
	function (e) {
		// error handling here
	}
);
Clone this wiki locally