Advertisement
Guest User

Untitled

a guest
Nov 24th, 2015
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.48 KB | None | 0 0
  1. // We will be using jQuery to manipulate DOM elements for the chat.
  2. var $ = require('jquery');
  3.  
  4. // Manages the state of our access token we got from the server
  5. var accessManager;
  6.  
  7. // Our interface to the IP Messaging service
  8. var messagingClient;
  9.  
  10. // A handle to the "general" chat channel - the one and only channel we
  11. // will have in this app
  12. var generalChannel;
  13.  
  14. // The object we are going to export as this module
  15. module.exports = {
  16. printMessage: function(msg, by) {
  17. var p = $('<p>').text(msg);
  18. if (by) {
  19. p.prepend($('<span class="message-by">').text(by + ': '));
  20. } else {
  21. p.addClass('server');
  22. }
  23. $('.messages').append(p);
  24. },
  25.  
  26. // Connect to the Twilio IP Messaging API and set up the chat app
  27. initializeChat: function(identity) {
  28.  
  29. // Get an access token for the current user, passing a username (identity)
  30. // and a device ID - for browser-based apps, we'll always just use the
  31. // value "browser"
  32. $.getJSON('/token', {
  33. identity: identity,
  34. device: 'browser'
  35. }, function(data) {
  36. // Initialize the IP messaging client
  37. accessManager = new Twilio.AccessManager(data.token);
  38. messagingClient = new Twilio.IPMessaging.Client(accessManager);
  39.  
  40. // Get the general chat channel, which is where all the messages are
  41. // sent in this application
  42. var promise = messagingClient.getChannelByUniqueName('general');
  43. promise.then(function(channel) {
  44. generalChannel = channel;
  45. this.channel = generalChannel;
  46. if (!generalChannel) {
  47. // If it doesn't exist, let's create it
  48. messagingClient.createChannel({
  49. uniqueName: 'general',
  50. friendlyName: 'General Chat Channel'
  51. }).then(function(channel) {
  52. console.log('Created general channel:');
  53. console.log(channel);
  54. generalChannel = channel;
  55. this.setupChannel();
  56. }.bind(this));
  57. } else {
  58. console.log('Found general channel:');
  59. console.log(generalChannel);
  60. this.setupChannel();
  61. }
  62. }.bind(this));
  63. }.bind(this));
  64. },
  65.  
  66. // Set up channel after it has been found
  67. setupChannel: function() {
  68. var onMessageAdded = function(newMessage) {
  69. this.printMessage(newMessage.body, newMessage.author);
  70. }.bind(this);
  71.  
  72. // Join the general channel
  73. generalChannel.join().then(function(channel) {
  74. // Listen for new messages sent to the channel
  75. generalChannel.on('messageAdded', onMessageAdded);
  76. });
  77. }
  78. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement