Created
July 21, 2014 11:23
-
-
Save konalegi/d5cd4273ad6300488b87 to your computer and use it in GitHub Desktop.
chat
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ChatApp = angular.module('ChatApp', []); | |
ChatApp.config(function ($httpProvider) { | |
$httpProvider.defaults.headers.common['X-CSRF-TOKEN'] = $("meta[name=\"csrf-token\"]").attr("content"); | |
}); | |
ChatApp.controller('ChatController', function ($scope, $http) { | |
$scope.messages = []; | |
$scope.send = function () { | |
var message = $scope.new_message; | |
$http.post('/chats', {'message': message}).success(function() {}); | |
$scope.new_message = ''; | |
}; | |
function start() { | |
if (!window.EventSource) { | |
alert('Your browser does not support SSE'); | |
} | |
var source; | |
function connect() { | |
source = new EventSource('/realtime/stream'); | |
} | |
connect(); | |
source.addEventListener('message', function (e) { | |
var message = JSON.parse(e.data); | |
$scope.$apply(function () { | |
$scope.messages.unshift(message); | |
}); | |
}, false); | |
source.addEventListener('error', function (e) { | |
if (e.readyState == EventSource.CLOSED) { | |
connect(); | |
} | |
}, false); | |
} | |
start(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment