Skip to content

Instantly share code, notes, and snippets.

@konalegi
Created July 21, 2014 11:23
Show Gist options
  • Save konalegi/d5cd4273ad6300488b87 to your computer and use it in GitHub Desktop.
Save konalegi/d5cd4273ad6300488b87 to your computer and use it in GitHub Desktop.
chat
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