Counting records in a table is obviously a manual effort until you guys get some of that spiffy new functionality already in the works ;)
However, I'm stuck on even using a manual run with .on('value', ...) to fetch a count:
var table = new Firebase('http://beta.firebase.com/user/tablename');
var count = 0;
table.on('child_added', function(snapshot) {
count++;
// how do I know if this is the last child? i.e. the count is complete?
});
// when is it okay to use count?
I foresee the same issues with any sort of pagination and I feel like I'm being a bit blockheaded about this. What am I missing?
Is this fundamentally the wrong pattern for, say, getting the number of messages a user has in his/her queue?
The child_added event has no notion of "done", since children can continue to be added over time. If you want to get a count of the children right now, you can use 'value' to get the current snapshot from that location and then count the children. For example:
table.once('value', function(snapshot) {
var count = 0;
snapshot.forEach(function(childSnapshot) {
count++;
});
// do something with count.
});
Alternatively, if you want the count to continually update, you can use .on() instead of .once() above. But this isn't ideal performance-wise, since you'll be counting all of the children every time. Fortunately, you can use a combination of 'child_added' and 'value' to efficiently keep a count:
var count = 0;
table.on('child_added', function(snapshot) {
count++;
// how do I know if this is the last child? i.e. the count is complete?
});
table.on('value', function(snapshot) {
// do something with count.
});
This works since 'value' will fire once after the "initial" data is complete and then again whenever the data changes, so you'll get a continually updating correct count. Though you'll need to handle child_removed as well if you expect children to be removed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With