Lesson 32. Adding a Chat Notification Indicator

Your chat page is coming together. Now users can log in and view the most recent chat messages, whether they were sent moments or weeks ago. The chat page currently facilitates all the visual aspects of your application’s chat functionality. The nice thing about socket.io is that it doesn’t need to exist on one page. Because your chat works by emitting and handling events, you can use those events in other ways. In this lesson, you build a custom event emitter to notify all active users when chat messages are being submitted. Then you build a small visual indicator in the navigation bar that animates when new messages are being shared. Through this small feat, users get a visual indication of an active chat room even when they’re browsing a different page.

This lesson covers

  • Broadcasting a custom event
  • Animating an icon in response to an event

Consider this

Users are enjoying the chat page in your application, but they’d like to browse other pages in your application instead of waiting for new messages to arrive on the chat page. They don’t want to miss out when the chat is active again, however. In this lesson, you rely on a custom event emitted by the server to animate a navigation-bar icon. When this icon is animated, users on any page of the application know that a chat is active.

32.1. Broadcasting to all other sockets

One thing to know about socket.io is that it can be configured to work over multiple specific chat rooms and different namespaces. It can even allow users to be added and removed from specific groups. In addition to these features, messages don’t always need to be emitted to every client. In fact, it doesn’t always make sense to emit a message to everyone if, for example, the client emitting the message is disconnecting.

In this section, you implement a new feature to notify all other users in the chat when a user’s socket disconnects. To do so, add the code in listing 32.1 to chatController.js within the io.on("connect") block.

In this code, you’re listening for when a certain client disconnects. You used this code block before to log a message to your console. In addition to logging this information, use client.broadcast.emit("user disconnected") to send a message to every socket aside from the one emitting the message. client.broadcast sends a custom event called 'user disconnected' to the connected chat users.

The reason you’re broadcasting the message instead of emitting it is because the client that’s emitting the message is disconnected and can no longer handle that custom event. You can use broadcast to emit to all other sockets even when the emitting socket isn’t disconnected, though.

Listing 32.1. Broadcasting event to all other users in chatController.js
client.on("disconnect", () => {
  client.broadcast.emit("user disconnected");          1
  console.log("user disconnected");
});

  • 1 Broadcast a message to all otherconnected sockets.

With this new event being emitted, you need to handle it on the client side. As with your other events, listen for the "user disconnected" event, and print some indication in the chat box. Add the event handler in listing 32.2 to recipeApp.js. In this code, you reuse your displayMessage to post a hardcoded message to let other users know that someone disconnected.

Listing 32.2. Displaying a message when a user disconnects in recipeApp.js
socket.on("user disconnected", () => {        1
  displayMessage({
    userName: "Notice",
    content: "User left the chat"
  });
});

  • 1 Listen for the ‘user disconnected’ event, and display a custom message.

Now relaunch your application, and log into multiple accounts by logging in on two different browsers or by using your browser’s incognito mode to log in with a new session. With two chat windows open side by side, you should see when one of the users is connected in the other chat box. In figure 32.1, the left chat window shows that a user disconnected when the right window is refreshed. In this case, a page refresh results in an immediate connection thereafter.

Figure 32.1. Displaying user disconnects in chat

Quick check 32.1

Q1:

What’s the difference between client.broadcast.emit and client.emit?

QC 32.1 answer

1:

client.broadcast.emit emits an event to all sockets except for itself, and client.emit emits an event to all sockets including itself.

 

32.2. Creating a chat indicator in navigation

The last addition you’ll make to your chat application is a feature to let users on other pages in the application know when there’s activity on the chat page. This feature could be helpful to users who are viewing their profiles or recipes, or hanging out on the home page; they might like to know that other users are awake and talking to one another in the chat room. To add this feature, add an icon to the navigation bar. When a message is submitted in the chat room, you animate the chat icon in the navigation bar to let users elsewhere know of chat activity.

First, add the icon to your navigation bar by adding <a href="/chat" class="chat-icon"> @</a> in layout.ejs. With this icon in place, you should see @ in your navigation bar the next time you relaunch your application. If you click this icon, it takes you to the /chat route.

Next, animate the icon by having it flash twice when any user sends a message. To accomplish this task, use jQuery’s fadeOut and fadeIn methods on the chat icon whenever a "message" event is received. Modify your socket.on("message") handler in recipe-App.js to look like the code in the next listing. In this example, you still use the displayMessage function to post the message to your chat view; then, with a simple for loop, you animate the chat icon to flash twice.

Listing 32.3. Animating chat icon when messages are sent in recipeApp.js
socket.on("message", (message) => {
  displayMessage(message);
  for (let i = 0; i < 2; i++) {
    $(".chat-icon").fadeOut(200).fadeIn(200);         1
  }
});

  • 1 Animate the chat icon to flash when a message is sent.

Relaunch your application, and log in to two browsers under two different accounts. Notice that now when one user sends a message, the other user sees the chat icon flash twice in the navigation bar, no matter where in the application they are (figure 32.2).

Figure 32.2. Animating the chat icon in the navigation bar

In lesson 33, you apply these steps and fully implement a chat feature in your capstone project.

Quick check 32.2

Q1:

True or false: You can handle socket.io events on any page in your application.

QC 32.2 answer

1:

True. For the example in this lesson, you imported the socket.io library in the layout.ejs file, which is used in every view. Similarly, your client-side JavaScript lives in files also imported to your layout file. If you were to import socket.io client only on a specific view, you’d be able to handle events only on that specific page.

 

Summary

In this lesson, you learned how to customize your socket.io events for use outside the normal chat feature. Because events can be used in any part of the application that has a socket.io client, you can create events for many types of data transfer over an open connection. First, you created a new event to notify other users when a user disconnects. Then you used an existing event to trigger a nonchat feature in your layout’s navigation. With this chat feature functioning, it’s time to apply the same tools to your capstone project (lesson 33). Then it’s time to deploy!

Try this

Now that your chat application has a feature that lets users know when a user has disconnected, it would be useful to know when a user connects. Use io.on("connection") to trigger a new event to your client to let them know that a new user has joined the chat.

When you’re done, see whether you can add the user’s name in the connection message, as in Notice: Jon Wexler has joined the chat.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.194.57