Prompting for Username

It would be really cool to be Wonder Woman. But it is more cool to be a JavaScript developer using Chattrbox. (Especially because real users actually have Gravatars.) In order to know who is using Chattrbox, you will need to prompt users for their usernames.

It is the responsibility of the dom module to interact with the UI, so create a promptForUsername function in dom.js. Add it to the exports instead of making it part of ChatForm or ChatList.

...
function createGravatarUrl(username) {
  let userhash = md5(username);
  return `http://www.gravatar.com/avatar/${userhash.toString()}`;
}

export function promptForUsername() {
  let username = prompt('Enter a username');
  return username.toLowerCase();
}
...

In the promptForUsername function, you created a let variable to hold the text entered by the user. (The prompt function is built into the browser and returns a string.) Then you returned a lowercase version of that text.

Next, you will need to update app.js to use this new function. Update the import statement for the dom module and call the promptForUsername function to get a value for the username variable:

import socket from './ws-client';
import {ChatForm, ChatList, promptForUsername} from './dom';

const FORM_SELECTOR = '[data-chat="chat-form"]';
const INPUT_SELECTOR = '[data-chat="message-input"]';
const LIST_SELECTOR = '[data-chat="message-list"]';

let username = '';
username = promptForUsername();

class ChatApp {
  ...

Now, update ChatMessage to use that username as the default. Remember, only messages received from the server have a data.user value.

...
class ChatMessage {
  constructor({
    message: m,
    user: u='batman', username,
    timestamp: t=(new Date()).getTime()
...

Finally, pass the username to the ChatList constructor:

...
class ChatApp {
  constructor() {
    this.chatForm = new ChatForm(FORM_SELECTOR, INPUT_SELECTOR);
    this.chatList = new ChatList(LIST_SELECTOR, 'wonderwoman' username);
    ...

After the build process completes, reload your browser and enter a username in the prompt (Figure 18.5).

Figure 18.5  Prompting for a username

Prompting for a username

Now, try sending messages. You should see your selected username echoed back at you, as well as the Gravatar associated with that username (Figure 18.6).

Figure 18.6  Your user’s name

Your user’s name

Gravatars are assigned using email addresses. If you do not have one associated with your email address, try [email protected] or [email protected].

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

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