【问题标题】:How to reorder children by priority in Firebase/angularFire如何在 Firebase/angularFire 中按优先级重新排序孩子
【发布时间】:2013-08-28 02:27:31
【问题描述】:

我正在尝试按孩子的数字优先级重新排序(交换)孩子。 这是我的尝试:

var swapChildrenByPriority = function(url, child1Priority, child2Priority){
  var ref = new Firebase(url);
  var child1, child2;
  ref.on('value', function(snap){
    snap.forEach(function(child){
      if(child.getPriority() === child1Priority){
        child1 = child;
      };
      if(child.getPriority() === child2Priority){
        child2 = child;
      };
    });
  });
  ref.child(child1.name()).setPriority(child2.getPriority());
  ref.child(child2.name()).setPriority(child1.getPriority());
};

您可以想象,这是行不通的。 调用此函数时,Chrome 的控制台会向我抛出错误:

TypeError: Cannot call method 'name' of undefined
Uncaught TypeError: Cannot call method 'name' of undefined

看起来好像孩子们没有设置优先级,但实际上他们这样做了。如果我在 Forge 中导入我的数据,所有孩子都拥有属性“.priority”:5.0。
当我再次调用该函数时,为了确保我得到了这个:

TypeError: Object https://test.firebaseio.com/testPriority has no method 'child'

在 Firebase 中执行此操作的正确方法是什么?
另外,如何在 AngularFire 中做同样的事情,以便使用 angularFire 服务的指令范围内的数据相应地重新排序,并刷新视图?

非常感谢您的宝贵时间,
问候
贾里德

【问题讨论】:

    标签: javascript angularjs firebase angularfire


    【解决方案1】:

    将函数放在来自数据库的回调中:

    fb.on('value', function(snap){
        snap.forEach(function(child){
            if(child.getPriority() === child1Priority) {
                child1 = child;
            }
            if(child.getPriority() === child2Priority){
                child2 = child;
            };
        });
        ref.child(child1.name()).setPriority(child2.getPriority());
        ref.child(child2.name()).setPriority(child1.getPriority());
    });
    

    【讨论】:

    • 请再次查看我的问题。它在数据库的回调中。
    • 这个答案对我来说是正确的。在您的代码中,child1 和 child2 还没有被初始化,因为来自 on() 的回调可能还没有被调用。
    猜你喜欢
    • 2016-01-31
    • 1970-01-01
    • 1970-01-01
    • 2014-08-05
    • 1970-01-01
    • 1970-01-01
    • 2020-05-04
    • 1970-01-01
    • 2019-06-29
    相关资源
    最近更新 更多