【发布时间】:2014-10-22 08:42:24
【问题描述】:
我正在尝试跟踪某个路径在 firebase 中包含多少个子节点。我一直在尝试使用 on('child_added') 和 on('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>
【问题讨论】:
标签: javascript transactions firebase