Last active
June 21, 2016 05:21
-
-
Save simpulton/7867239 to your computer and use it in GitHub Desktop.
A real-time presence service using Firebase and AngularJS.
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
app.controller('MainCtrl', ['$scope', 'PresenceService', function ($scope, PresenceService) { | |
$scope.totalViewers = 0; | |
$scope.$on('onOnlineUser', function(){ | |
$scope.$apply(function () { | |
$scope.totalViewers = PresenceService.getOnlineUserCount(); | |
}); | |
}); | |
}]); | |
app.factory('PresenceService', ['$rootScope', function($rootScope){ | |
var onlineUsers = 0; | |
var listRef = new Firebase('https://<url>.firebaseio.com/presence/'); | |
var userRef = listRef.push(); | |
// Add ourselves to presence list when online. | |
var presenceRef = new Firebase('https://<url>.firebaseio.com/.info/connected'); | |
presenceRef.on('value', function (snap) { | |
if (snap.val()) { | |
userRef.set(true); | |
// Remove ourselves when we disconnect. | |
userRef.onDisconnect().remove(); | |
} | |
}); | |
// Number of online users is the number of objects in the presence list. | |
listRef.on('value', function (snap) { | |
onlineUsers = snap.numChildren(); | |
$rootScope.$broadcast('onOnlineUser'); | |
}); | |
var getOnlineUserCount = function() { | |
return onlineUsers; | |
} | |
return { | |
getOnlineUserCount: getOnlineUserCount | |
} | |
}]); |
I think the onDisconnect
call should go before the userRef.set
statement so you minimize the chances of ghost user leftover (logged-on user initiating a logout call that resolves before code makes it to onDisconnect)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Any idea about why it does not work in a different view? I use {{totalViewers}} in a different view but it returns to 0, I have to reload the site to be able to see the real number.