특정 경로에 firebase에 포함 된 자식 수를 추적하려고합니다. 나는 on ('child_added') 및 on ('child_removed') 콜백을 사용하여 카운트를 업데이트하려고 시도했지만 기존 자식에 대해서도 호출됩니다. Here은이를 증명하는 코드 is입니다. 또한 카운트가 항상 정확한지 확인하는 보안 규칙을 작성하고 싶지만 개체에있는 자식 수를 얻는 방법이 없다고 생각됩니다.Firebase에서 자식 수를 추적하는 방법
<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>