As far as I understand, JavaScript objects are an unordered collection of properties, whereas Firebase lists use IDs as property keys, which the docs say are chronologically ordered.
Taking Firebase's AngularFire chat code example (below), which stores messages as a Firebase list, the client presumably always displays the messages in the correct order, even though the object pointed to by $scope.messages
is, I assume, a JavaScript object like any other.
How are the messages always displayed in the correct order?
angular.module("myChatRoom", ["firebase"])
.factory("ChatService", ["$firebase", function($firebase) {
var ref = new Firebase("https://<my-firebase>.firebaseio.com/chat");
return $firebase(ref);
}])
.controller("ChatController", ["$scope", "ChatService",
function($scope, chatService) {
$scope.user = "Guest " + Math.round(Math.random()*101);
$scope.messages = chatService;
$scope.addMessage = function() {
$scope.messages.$add({from: $scope.user, content: $scope.message});
$scope.message = "";
};
}
]);
HTML:
<html ng-app="myChatRoom">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js"></script>
<script src="//cdn.firebase.com/js/client/1.0.6/firebase.js"></script>
<script src="//cdn.firebase.com/libs/angularfire/0.7.1/angularfire.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="ChatController">
<ul ng-repeat="message in messages">
<li>{{message.from}}: {{message.content}}</li>
</ul>
<form ng-submit="addMessage();">
<input type="text" ng-model="message"/>
<input type="submit" value="Send Message"/>
</form>
</body>
</html>
Other Firebase examples use .on('child_added', cb)
and new messages are added to an array in the callback, or are simply displayed. With these examples I understand how the messages are displayed in order as I'm guessing that the callback is passed the message snapshots in the order determined by Firebase. However that isn't the case with the example above.