[英]How to get the key as soon as value gets changed in firebase?
I have my firebase structure like this我有这样的 firebase 结构
I want to get a the key/number as soon as status becomes 1.我想在状态变为 1 时立即获得密钥/号码。
I tried..我试过了..
//Listen for number
var ref = firebase.database().ref("games/" + gameId + "/numbers");
ref.orderByChild('status').equalTo('1').on("value", function(snapshot)
{
snapshot.forEach((function(child){
console.log(child.key);
}));
});
But every time status gets updated i am getting every number with the status = 1. I want just the last updated number.但是每次状态更新时,我都会得到状态 = 1 的每个数字。我只想要最后更新的数字。
When you listen for the value
event, you get a snapshot with all matching data each time.当您侦听
value
事件时,您每次都会获得包含所有匹配数据的快照。
If you want to get more granular notifications, you can listen for child_*
events.如果您想获得更精细的通知,您可以监听
child_*
事件。 For example to hear when a node status gets set to one, you can listen for child_added
:例如,要听到节点状态何时设置为 1,您可以监听
child_added
:
ref.orderByChild('status').equalTo('1').on("child_added", function(snapshot)
{
console.log(snapshot.key);
});
You'll note that I also remove the forEach
.您会注意到我还删除了
forEach
。 Since child_
events fire for each individual child, you no longer need the loop.由于
child_
事件会针对每个单独的孩子触发,因此您不再需要循环。
If you find it hard to figure out which child_
event to listen to, I find it easiest to think of the query as a "view" on the data.如果您发现很难确定要听哪个
child_
事件,我发现将查询视为数据的“视图”最容易。 When a child node's status is set to 1, it enters the view, so it is child_added
.当子节点的状态设置为 1 时,它进入视图,所以它是
child_added
。 When a child node's status is set to another value, it leaves the view, so it'd fire child_removed
.当子节点的状态设置为另一个值时,它会离开视图,因此会触发
child_removed
。
use child_changed
instead of value
.使用
child_changed
而不是value
。 It will only return single value in which child will be changed so we will get key directly by snapshot.key
.它只会返回单个值,其中孩子将被更改,因此我们将直接通过
snapshot.key
获取密钥。
//Listen for number
var ref = firebase.database().ref("games/" + gameId + "/numbers");
ref.orderByChild('status').equalTo('1').on("child_changed", function(snapshot)
{
console.log(snapshot.key);
});
I think, it will be helpful for you.我想,这对你会有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.