io.socket.on()

Starts listening for server-sent events from Sails with the specified eventIdentity. Will trigger the provided callback function when a matching event is received.

Usage

  1. io.socket.on(eventIdentity, function (msg) {
  2. // ...
  3. });
Argument Type Details
1 eventIdentity ((string)) The unique identity of a server-sent event, e.g. “recipe”
2 callback ((function)) Will be called when the server emits a message to this socket.
Callback
Argument Type Details
1 msg ((object)) Message sent from the Sails server

Note that the callback will NEVER trigger 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:

Resourceful Pubsub Methods
Low-Level Socket Methods
  • server emits a message to all known sockets (see sails.sockets.blast())
  • server emits a message directly to this socket (io.socket) using its unique id (see sails.sockets.emit())
  • server broadcasts to a room in which this socket (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)

Example

Listen for new orders and updates to existing orders:

  1. io.socket.on('order', function onServerSentEvent (msg) {
  2. // msg => {...whatever the server published/emitted...}
  3. });
Another example, this time using Angular:

Note that this Angular example assumes the backend calls publishCreate() at some point.

  1. angular.module('cafeteria').controller('CheckoutCtrl', function ($scope) {
  2. $scope.orders = $scope.orders || [];
  3. if (!io.socket.alreadyListeningToOrders) {
  4. io.socket.alreadyListeningToOrders = true;
  5. io.socket.on('order', function onServerSentEvent (msg) {
  6. // Let's see what the server has to say...
  7. switch(msg.verb) {
  8. case 'created':
  9. $scope.orders.push(msg.data); // (add the new order to the DOM)
  10. $scope.$apply(); // (re-render)
  11. break;
  12. default: return; // ignore any unrecognized messages
  13. }
  14. });
  15. }
  16. });

Notes

  • 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.