我试图跟踪某个路径在firebase中包含多少个孩子。我一直在尝试使用on(' child_added')和(' child_removed')回调来更新计数,但即使现有的孩子也会调用它们。 Here是一个展示这一点的代码。我还希望能够编写一个安全规则来确保计数总是正确的,但似乎没有办法获得对象中的子数。
<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>
答案 0 :(得分:1)
{<1}}和child_added
事件将针对每个已添加到客户端的孩子触发,因此从服务器下载的所有内容(或本地添加的)。< / p>
你想保留一个单独的child_removed
是个好主意。但是,您应该从postcount
和child_added
触发它,而不是从child_removed
和addPost
触发它。
这样的事情:
removePost
请注意,您的代码目前是各种方法的混合搭配。如果您已经收到所有帖子,则可以在那里统计:
addPost: function () {
var self = this;
self.ref.child('posts').push({content: 'YO'}, function(error) {
if (!error) {
self.ref.child('postsCount').transaction(function (count) {
return count + 1;
});
}
});
},
removePost: function () {
if (this.keys.length > 0) {
var self = this;
var topId = self.keys[0];
self.ref.child('posts/' + topId).remove(function(error) {
if (!error) {
self.ref.child('postsCount').transaction(function (count) {
return count - 1;
});
}
});
}
},