在子值更改事件的回调内部时,child_added快照中缺少Firebase数据

时间:2013-08-22 17:05:53

标签: firebase

我尝试在用户“激活”其帐户后向用户显示所有用户数据(包括当前用户)时遇到此问题。当收听列表中项目的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' } }

有谁知道这里发生了什么?

1 个答案:

答案 0 :(得分:0)

将事件附加到另一个事件中是错误的......没有必要......

示例:

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});