Total number of records in Firebase (when am I done counting?)

前端 未结 3 1483
小蘑菇
小蘑菇 2020-12-19 16:33

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

3条回答
  •  一整个雨季
    2020-12-19 17:13

    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.

提交回复
热议问题