Skip to content
This repository was archived by the owner on Aug 13, 2021. It is now read-only.

Overview

sgress454 edited this page Apr 30, 2014 · 2 revisions

The most important / interesting files in the sailsChat app are:

The definition of the User model class, including the afterPublishUpdate method which sends notifications to public chat rooms when a user changes their name. Also notable for its use of the autosubscribe property.

The definition of the Room model class, including the afterPublishRemove method which checks whether anyone is left in a chat room after a user leaves, and sends notifications as necessary. Also notable for its use of the autosubscribe property.

Contains the onConnect and onDisconnect methods that, in this app, control user creation / destruction. Because this (admittedly trivial) app creates one user per socket, rather than per browser session, it means that a browser session can contain multiple users. Whenever a user is created, sailsChat stores its socket ID in the session so we can look up users by socket ID later (like when the socket disconnects, or a chat message is sent). Note that onConnect is the only place where a socket is subscribed to the message context of a User model--this means that the only sockets that will receive messages via User.message() are the ones that the user itself is connected to.

The Room controller contains join and leave methods that handle subscribing/unsubscribing the requesting socket to/from a public chat room. This enables them to receive chat messages sent to that room, while keeping those sockets that are not in the room from getting the messages. You could allow everyone to get all the public messages and then filter out the ones you don't care about on the front end, but the point here is to a) reduce network traffic and b) reduce unnecessary code-writing. Note the use of next() at the end of the join and leave controller actions; this allows Sails to keep matching the routes that triggered those actions. In this case, it means the blueprint add and remove actions will be triggered (see /config/routes.js below).

Here, the RoomController.join and RoomController.leave actions are bound to the same routes that, by default, trigger the blueprint add to room.users and remove from room.users actions. Since the custom join and leave actions call next() at the end instead of returning a response, the blueprint actions still get executed.

The main front-end Javascript file. Methods are spread across several other files, but this is the one that is the most interesting from a PubSub perspective: it contains the code which handles the socket events from the server.

Clone this wiki locally