It's cool how we can now see real-time changes in a part of the Notes application. Let's turn to the /notes/view page to see what we can do. What comes to mind is this functionality:
- Update the note if someone else edits it
- Redirect the viewer to the home page if someone else deletes the note
- Allow users to leave comments on the note
For the first two features, we can rely on the existing events coming from the Notes model. The third feature will require a messaging subsystem, so we'll get to that later in this chapter.
In routes/notes.mjs, add this to the end of the module:
export function socketio(io) {
notes.events.on('noteupdate', newnote => {
io.of('/view').emit('noteupdate', newnote);
});
notes.events.on('notedestroy', data => {
io.of('/view').emit('notedestroy', data);
});
};
At the top of app.mjs, make this change:
import { socketio as indexSocketio, router as index } from './routes/index';
import { router as users, initPassport } from './routes/users';
import { socketio as notesSocketio, router as notes } from './routes/notes'; Uncomment that line of code in app.mjs because we've now implemented the function we said we'd get to later:
indexSocketio(io);
notesSocketio(io);
This sets up the Notes application to send noteupdate and notedestroy messages when notes are updated or destroyed. The destination is the /view namespace. We'll need to make a corresponding modification to the note view template so it does the right thing. This means any browser viewing any note in the application will connect to this namespace. Every such browser will receive events about any note being changed, even those notes that are not being viewed. This means that the client code will have to check the key, and only take action if the event refers to the note being displayed.