- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我正在尝试测试 Firebase 以允许用户使用 push
发表评论。我想用以下内容显示我检索到的数据;
fbl.child('sell').limit(20).on("value", function(fbdata) {
// handle data display here
}
问题是数据是按从旧到新的顺序返回的——我希望它按相反的顺序返回。 Firebase 可以做到这一点吗?
最佳答案
Since this answer was written, Firebase has added a feature that allows ordering by any child or by value. So there are now four ways to order data: by key, by value, by priority, or by the value of any named child. See this blog post that introduces the new ordering capabilities.
The basic approaches remain the same though:
1. Add a child property with the inverted timestamp and then order on that.
2. Read the children in ascending order and then invert them on the client.
Firebase 支持通过两种方式检索集合的子节点:
您现在得到的是名称,恰好是按时间顺序排列的。顺便说一句,这不是巧合:当您push
一个项目到一个集合中时,会生成名称以确保子项以这种方式排序。引用Firebase documentation for push
:
The unique name generated by push() is prefixed with a client-generated timestamp so that the resulting list will be chronologically-sorted.
Firebase guide on ordered data关于这个话题有话要说:
How Data is Ordered
By default, children at a Firebase node are sorted lexicographically by name. Using
push()
can generate child names that naturally sort chronologically, but many applications require their data to be sorted in other ways. Firebase lets developers specify the ordering of items in a list by specifying a custom priority for each item.
获得所需行为的最简单方法是在添加项目时也指定一个始终递减的优先级:
var ref = new Firebase('https://your.firebaseio.com/sell');
var item = ref.push();
item.setWithPriority(yourObject, 0 - Date.now());
您还必须以不同的方式检索 child :
fbl.child('sell').startAt().limitToLast(20).on('child_added', function(fbdata) {
console.log(fbdata.exportVal());
})
在我的测试中,使用 on('child_added'
确保最后添加的几个 child 按时间倒序返回。另一方面使用 on('value'
, 以他们的名字的顺序返回他们。
请务必阅读 section "Reading ordered data" ,它解释了使用 child_*
事件来检索(排序的)子项。
一个 bin 来证明这一点:http://jsbin.com/nonawe/3/watch?js,console
关于javascript - 按发布降序显示帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38063552/
我是一名优秀的程序员,十分优秀!