Start listening for server-sent events from Sails with the specified eventIdentity
. Will trigger the provided callback function when a matching event is received.
io.socket.on(eventIdentity, function (msg) {
// ...
});
Argument | Type | Details | |
---|---|---|---|
1 | eventIdentity |
The unique identity of a server-sent event, e.g. "recipe" | |
2 | handlerFn |
Will be called when the server emits a message to this socket. |
Argument | Type | Details | |
---|---|---|---|
1 | msg |
The message broadcasted from the Sails server. |
Note that the event handler will NEVER be called until one of your back-end controllers, models, services, etc. sends a message to this socket. Typically that is achieved one of the following ways:
eventIdentity
(see Model.publishCreate(http://sailsjs.com/documentation/reference/web-sockets/resourceful-pub-sub/publish-create) and Model.watch())sails.sockets
)io.socket
) using its unique id (see sails.sockets.emit())io.socket
) has been allowed to join (remember that a socket only stays subscribed as long as it is connected-- i.e. as long as the browser tab is open)Listen for new orders and updates to existing orders:
io.socket.on('order', function onServerSentEvent (msg) {
// msg => {...whatever the server broadcasted...}
});
Note that this Angular example assumes the backend calls
publishCreate()
at some point.
angular.module('cafeteria').controller('CheckoutCtrl', function ($scope) {
$scope.orders = $scope.orders || [];
if (!io.socket.alreadyListeningToOrders) {
io.socket.alreadyListeningToOrders = true;
io.socket.on('order', function onServerSentEvent (msg) {
// Let's see what the server has to say...
switch(msg.verb) {
case 'created':
$scope.orders.push(msg.data); // (add the new order to the DOM)
$scope.$apply(); // (re-render)
break;
default: return; // ignore any unrecognized messages
}
});
}
});
If a socket's connection to the server was interrupted-- perhaps because the server was restarted, or the client had some kind of network issue-- it is possible to handle connect
and disconnect
events and manually reconnect the socket again. sails.io.js
does this for you automatically, but you can also bind your own handlers. While this is not recommended for 99% of apps, usage is documented below for completeness:
io.socket.on('connect', function(){
io.socket.get('/messages');
io.socket.get('/notifications/subscribe/statusUpdates');
});
io.socket.on('disconnect', function(){
console.log('Lost connection to server');
});
- When listening for resourceful pubsub calls, the
eventIdentity
is the same as the identity of the calling model (e.g. if you have a model "UserComment", the identity is "usercomment".)- For context-- these types of server-sent events are sometimes referred to as "comet") messages.