gpt4 book ai didi

javascript - 如何在 Firebase 中跟踪 child 数量

转载 作者:行者123 更新时间:2023-12-03 11:36:15 24 4
gpt4 key购买 nike

我正在尝试跟踪特定路径在 firebase 中包含多少个子节点。我一直在尝试使用 on('child_added') 和 on('child_removed') 回调来保持计数更新,但即使是现有的 child 也会调用它们。 Here是一个 codepen 演示了这一点。我还希望能够编写一条安全规则来确保计数始终正确,但似乎没有办法获取对象中子级的数量。

<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>

最佳答案

child_addedchild_removed 事件将为添加到客户端的每个子项触发,因此从服务器下载的所有内容(或本地添加)。

您保留单独的postcount的想法是个好主意。但您不应从 child_addedchild_removed 触发它,而应该从 addPostremovePost 触发它。

类似这样的事情:

  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;
});
}
});
}
},

请注意,您的代码当前是多种方法的混合和匹配。如果您已经获得了所有帖子,您可以简单地在那里计算它们:

    self.ref.child('posts').on('value', function (snap) {
self.posts = snap.val();
self.keys = Object.keys(self.posts);
self.count = snap.numChildren();
});

关于javascript - 如何在 Firebase 中跟踪 child 数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26497677/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com