Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
589 views
in Technique[技术] by (71.8m points)

javascript - How to keep track of children count in Firebase

I'm trying to keep track of how many children a certain path contains in firebase. I've been trying to use the on('child_added') and on('child_removed') callbacks to keep a count updated, but they get called even for existing children. Here is a codepen demonstrating this. I would also like to be able to write a security rule that makes sure the count is always correct, but it seems there isn't a way to get the number of children in an object.

<script src="http://www.polymer-project.org/platform.js"></script>
<link rel="import" href="http://www.polymer-project.org/components/polymer/polymer.html">

<script src="https://cdn.firebase.com/js/client/1.1.2/firebase.js"></script>

<polymer-element name="my-element">
  <template>
    <div>
      <h1>Posts ({{count}})</h1>
      <template repeat="{{key in keys}}">
        <span>{{posts[key].content}} </span>
      </template></br>
      <button on-click="{{addPost}}">Add Post</button>
      <button on-click="{{removePost}}">Remove Post</button>
    </div>
  </template>
  <script>
    Polymer('my-element', {
      addPost: function () {
        var self = this;
        self.ref.child('posts').push({content: 'YO'});
      },
      removePost: function () {
        if (this.keys.length > 0) {
          var self = this;
          var topId = self.keys[0];
          self.ref.child('posts/' + topId).remove();    
        }
      },
      ready: function () {
        var baseUrl = "https://transaction-test.firebaseio.com";
        var self = this;
        self.ref = new Firebase(baseUrl);
        self.ref.child('posts').on('value', function (snap) {
          self.posts = snap.val();
          self.keys = Object.keys(self.posts);
        });
        self.ref.child('postsCount').on('value', function (snap) {
          self.count = snap.val();
        });
        self.ref.child('posts').on('child_added', function (snap) {
          self.ref.child('postsCount').transaction(function (count) {
            return count + 1;
          });
        });
        self.ref.child('posts').on('child_removed', function (snap) {
          self.ref.child('postsCount').transaction(function (count) {
            return count - 1;
          });
        });
      }
    });
  </script>
</polymer-element>
<my-element></my-element>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...