-
Notifications
You must be signed in to change notification settings - Fork 0
The anatomy of a ChatJS adapter
The adapter is the piece of code that will determine how ChatJS will communicate to the server. When you initialize ChatJS, you pass the adapter as the parameter. Example:
$(function () {
$.chat({
// A lot of ChatJS options go here.
// And this is your brand new adapter:
adapter: new BareboneAdapter()
});
});
A barebone adapter looks like this:
function BareboneAdapter(options) {
this.defaults = {
// put your options here
};
this.opts = $.extend({}, this.defaults, options);
}
BareboneAdapter.prototype = {
init: function (chat, done) {
// this object with these functions must exist because ChatJS will
// call them
this.server = {
sendMessage: function (otherUserId, messageText, clientGuid, done) { done(); },
sendTypingSignal: function (otherUserId, done) { done(); },
getMessageHistory: function (otherUserId, done) { done(); },
getUserInfo: function (userId, done) { done(); },
getUsersList: function (done) { done(); },
};
}
}
So, let's say that ChatJS wants to use your adapter to send a message to a user. It will just call adapter.server.sendMessage()
. Simple isn't it? It's the same for all functions. All you have to do is to implement these functions according to your own protocol.
But let's say that your adapter, by whatever means, found out that the current user has received a new message. How does your adapter tells ChatJS that this happened? The init
function of your adapter receives the chat
instance. This instance contains an object called client
full of functions your adapter call call. This is the anatomy of the client
object:
{
sendMessage: function (message) { },
sendTypingSignal: function (otherUserId) { },
usersListChanged: function (usersList) { },
showError: function (errorMessage) { }
}
So, let's say you have implemented a socket mechanism to connect to your server and your socket trigger JavaScript events. You could implement your adapter like this:
BareboneAdapter.prototype = {
init: function (chat, done) {
// this *hypothetical* socket object triggers events on new messages
$.socket.on("new-message", function(message) {
// calls the chat instance to push the message that "socket" just received from the server
chat.client.sendMessage(message);
});
}
}