snap.ref.remove()将删除父级中的所有节点,而不仅仅是本身 [英] snap.ref.remove() is removing all the nodes in the parent rather than just itself

查看:92
本文介绍了snap.ref.remove()将删除父级中的所有节点,而不仅仅是本身的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想删除前2个节点,但是它删除了整个分支。如果我注释掉remove(),它正确的console.logs前2个节点,但是当我取消注释remove()它删除该messagesRef中的所有节点,而不是只有前2名。

  messagesRef.limitToFirst(2).on('child_added',function(snap){
snap.ref()。remove();
console.log(snap.val());

});


解决方案

这是因为一旦您删除了一个,现在是一个新child_added到2极限,所以它会不断循环,直到他们都被删除。

 子项目1 
子项目2

- >>删除子项目1

子项目2
子项目3 - >新增child_added事件

等...

为了解决这个问题,您可以保留一个计数器:

  var numRemoved = 0; 
var ref = messagesRef.limitToFirst(2);
ref.on('child_added',removeFirstTwoChildren);
removeFirstTwoChildren(snap){
snap.ref()。remove();
console.log(snap.val());
numRemoved ++;
if(numRemoved === 2){
ref.off('child_added',removeFirstTwoChildren);
}
}


I was just trying to remove the top 2 nodes, but it removes the entire branch instead. If I comment out the remove(), it correctly console.logs the top 2 nodes, but when i uncomment the remove() it deletes all the nodes in that messagesRef, not just the top 2.

messagesRef.limitToFirst(2).on('child_added', function (snap) {
    snap.ref().remove();
    console.log(snap.val());

});

解决方案

This is because once you've removed one, there is now a "new" child_added into the limit of 2. So it'll continuously loop through them all until they are all deleted.

Child 1
Child 2

->>delete child 1

Child 2
Child 3 ->new child_added event

etc...

To get around this you can keep a counter:

var numRemoved = 0; 
var ref = messagesRef.limitToFirst(2);
ref.on('child_added', removeFirstTwoChildren);
removeFirstTwoChildren(snap){
    snap.ref().remove();
    console.log(snap.val());
    numRemoved++;
    if(numRemoved === 2){
        ref.off('child_added', removeFirstTwoChildren);
    }
}

这篇关于snap.ref.remove()将删除父级中的所有节点,而不仅仅是本身的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆