如何对使用“push()”创建的Firebase密钥进行排序?

时间:2014-12-28 02:57:58

标签: firebase angularfire

根据Firebase文档:

  

push()生成的唯一名称以a为前缀   客户端生成的时间戳,以便生成结果列表   按时间顺序排序。

那么当我从通过push创建所有子节点的节点检索列表时,如何将此对象转换为按时间顺序排序的数组?在AngularFire中,有一个$ asArray()方法似乎为你做了这个。如果没有AngularFire,我怎么能这样做?

我想要做的代码示例是:

var ref = new Firebase('https://your.firebaseio.com/')

ref.on('value', function(snap){
  var obj = snap.val()

  console.log(obj)

  /*
  obj looks like: {-JeHAy0QO5jhCAecc-Ha: {name: "item 1"} ..}. 
  I'd like to loop through this collection in
  chronology order, but in JS, one should not rely on the order that key values
  come while using a for-in loop. So I figured that instead, I probably need
  to transform it into an array first then use a regular for loop.

  Therefore, I'd like to transform obj into an array:
  [{name: 'item 1'}, {name: 'item 2'}, ..]
  where the order of the array is chronologically ordered (ie somehow decode 
  and use the keys of obj to sort the object). How do I do this?
  */
})

1 {/ 1}}下的script.js下的

http://plnkr.co/edit/yEcBK7PVTf7VxjnVhNXL?p=info

1 个答案:

答案 0 :(得分:4)

如果您尝试按照键的顺序将所有子项放入数组中,则可以使用DataSnapshot's forEach method

ref.on('value', function(snap){
  var children = [];
  snap.forEach(function(child) {
    children.push(child.val());
  });
  console.log(children.length);

forEach数组将以正确的顺序包含所有子项。

但请注意,每次添加/删除任何子项或修改任何现有子项时,都会触发此操作。如果您使用此数组来构建HTML DOM,则每次都会重新绘制整个集合。

这就是为什么Firebase还会针对特定孩子发起事件:child_addedchild_changedchild_removedchild_movedon的签名定义为:

  

on() - on(eventType, callback, [cancelCallback], [context])

回调函数记录为:

  

发生指定事件时触发的回调。回调将传递给DataSnapshot。出于订购目的,“child_added”,“child_changed”和“child_moved”也将按优先级顺序传递包含前一个子项的键的字符串(如果它是第一个子项,则返回null)。

因此,使用previousChild参数,您还可以重建正确的顺序(您只需自己完成)。

有关更多信息,请参阅Firebase documentation on these events

相关问题