当用户“激活”其帐户后,尝试向用户显示所有用户数据(包括当前用户)时,我遇到了此问题。当监听列表中某个项目的 onValue 更改,然后在回调中监听该列表的 child_added 事件时,原始“监视”项目的快照中会丢失数据。
人工繁殖:
var Firebase = require('firebase');
var rootRef = new Firebase('YOUR-FIREBASE-URL');
var userListRef = rootRef.child('users');
// Clearing the list
userListRef.remove();
// Create a list of users with at least two key/values
var firstUserRef = userListRef.push({name: 'me', active: false});
userListRef.push({name: 'you', active: false});
userListRef.push({name: 'someone', active: false});
// listen for a change to one of the users child data
firstUserRef.child('active').once('value', function(activeData){
// When the value change callback fires list all of the users data
userListRef.on('child_added', function(userData){
console.log(userData.val());
})
});
控制台输出:
{ active: false }
{ active: false, name: 'you' }
{ active: false, name: 'someone' }
名称数据去了哪里?这看起来不像预期的行为,也不是同步问题,因为名称数据应该已经在本地设置。如果我们修改代码来检索整个列表对象,如下所示:
// listen for a change to one of the users child data
firstUserRef.child('active').once('value', function(activeData){
// When the value change callback fires list all of the users data
userListRef.on('value', function(usersData){
console.log(usersData.val());
})
});
包含所有数据:
{ '-J1ayCVS6B_zVterQWJh': { active: false, name: 'me' },
'-J1ayCVUUAFP0TL77oaO': { active: false, name: 'you' },
'-J1ayCVUUAFP0TL77oaP': { active: false, name: 'someone' } }
有人知道这是怎么回事吗?
最佳答案
这是错误的,您将一个事件附加到另一个事件中。没有必要...
示例:
cars (parent node)
----- -J1ayCVS6B_zVterQWJh
----- -J1ayCVUUAFP0TL77oaO
----- -J1ayCVUUAFP0TL77oaP
获取更改
var ref = new Firebase('https://g.com/cars");
ref.on('value', function(snapshot) {
if (snapshot.val() != null) {
snapshot.forEach(function(itemDetails) {
itemDetails.val().username;
itemDetails.val().active;
});
}
});
//and to be serious first attach the event, then you push the records
//assume is a button_click
var ref2 = new Firebase('https://g.com/cars");
var firstUserRef = ref2.push({name: 'me', active: false});
firstUserRef.push({name: 'you', active: false});
firstUserRef .push({name: 'someone', active: false});
关于在子值更改事件的回调内时,child_added 快照中缺少 Firebase 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18386725/