gpt4 book ai didi

javascript - 按发布降序显示帖子

转载 作者:行者123 更新时间:2023-11-30 13:09:12 24 4
gpt4 key购买 nike

我正在尝试测试 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());

更新

您还必须以不同的方式检索子项:

fbl.child('sell').startAt().limitToLast(20).on('child_added', function(fbdata) {
console.log(fbdata.exportVal());
})

在我的测试中,使用 on('child_added' 确保最后添加的几个子项按时间倒序返回。另一方面,使用 on('value' ,按名称顺序返回它们。

请务必阅读section "Reading ordered data" ,它解释了如何使用 child_* 事件来检索(有序)子项。

用于演示这一点的垃圾箱:http://jsbin.com/nonawe/3/watch?js,console

关于javascript - 按发布降序显示帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38932010/

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