Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. new Vue({
  2.   el: '#app',
  3.  
  4.   data: {
  5.       ws: null, // Our websocket
  6.       newMsg: 'Hi', // Holds new messages to be sent to the server
  7.       chatContent: '', // A running list of chat messages displayed on the screen
  8.       email: null, // Email address used for grabbing an avatar
  9.       username: null, // Our username
  10.       joined: false // True if email and username have been filled in
  11.   },
  12.  
  13.   created: function() {
  14.       var self = this;
  15.       this.ws = new WebSocket('ws://' + window.location.host + '/');
  16.       this.ws.addEventListener('message', function(e) {
  17.           var msg = JSON.parse(e.data);
  18.           self.chatContent += '<div class="chip">'
  19.                   + '<img src="' + self.gravatarURL(msg.email) + '">' // Avatar
  20.                   + msg.username
  21.               + '</div>'
  22.               + emojione.toImage(msg.message) + '<br/>'; // Parse emojis
  23.  
  24.           var element = document.getElementById('chat-messages');
  25.           element.scrollTop = element.scrollHeight; // Auto scroll to the bottom
  26.       });
  27.   },
  28.  
  29.   methods: {
  30.       send: function () {
  31.           if (this.newMsg != '') {
  32.               this.ws.send(
  33.                   JSON.stringify({
  34.                       email: this.email,
  35.                       username: this.username,
  36.                       message: $('<p>').html(this.newMsg).text() // Strip out html
  37.                   }
  38.               ));
  39.               this.newMsg = ''; // Reset newMsg
  40.           }
  41.       },
  42.  
  43.       join: function () {
  44.           if (!this.email) {
  45.               Materialize.toast('You must enter an email', 2000);
  46.               return
  47.           }
  48.           if (!this.username) {
  49.               Materialize.toast('You must choose a username', 2000);
  50.               return
  51.           }
  52.           this.email = $('<p>').html(this.email).text();
  53.           this.username = $('<p>').html(this.username).text();
  54.           this.joined = true;
  55.       },
  56.  
  57.       gravatarURL: function(email) {
  58.           return 'http://www.gravatar.com/avatar/' + CryptoJS.MD5(email);
  59.       }
  60.   }
  61. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement