chatRoomNg.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. angular.module('tabooServices', [])
  2. .factory('connectionService', function($rootScope) {
  3. var WS = window['MozWebSocket'] ? MozWebSocket : WebSocket;
  4. var chatSocket = null;
  5. var service = {
  6. username: '',
  7. messages: [],
  8. members: [],
  9. error: null,
  10. isConnected: function() {
  11. return this.username != '';
  12. },
  13. };
  14. service.connect = function(username) {
  15. chatSocket = new WS(jsRoutes.controllers.Application.chat(username).webSocketURL());
  16. chatSocket.onmessage = onEvent;
  17. service.username = username;
  18. }
  19. service.disconnect = function() {
  20. service.username = '';
  21. service.messages = [];
  22. service.members = [];
  23. chatSocket.close();
  24. chatSocket = null;
  25. }
  26. service.send = function(message) {
  27. chatSocket.send(JSON.stringify({text: message}));
  28. }
  29. function onEvent(event) {
  30. var message = JSON.parse(event.data);
  31. if(message.error) {
  32. service.error = message;
  33. }
  34. else {
  35. service.messages.push(message);
  36. service.members = message.members;
  37. }
  38. $rootScope.$apply();
  39. }
  40. return service;
  41. });
  42. angular.module('taboo', ['tabooServices']);
  43. function partial(template) {
  44. return jsRoutes.controllers.Assets.at('partials/'+template+'.html').url;
  45. }
  46. function ViewCtrl($scope) {
  47. $scope.partial = partial;
  48. }
  49. function LoginCtrl($scope, connectionService) {
  50. $scope.service = connectionService;
  51. }
  52. function ChatCtrl($scope, connectionService) {
  53. $scope.service = connectionService;
  54. $scope.onType = function(event) {
  55. if(event.keyCode == 13) {
  56. connectionService.send($scope.text);
  57. $scope.text = '';
  58. event.originalEvent.preventDefault();
  59. }
  60. }
  61. }