Firebase.ServerValue.TIMESTAMP not synched between listeners and the client that actually adds data

前端 未结 2 951
面向向阳花
面向向阳花 2020-12-21 06:18

Here is the simplest example possible:

var fb = new Firebase(\'https://xxxxxxxxxxx.firebaseio.com/test\');

fb.limitToLast(1).on(\'child_added\', function(sn         


        
2条回答
  •  情话喂你
    2020-12-21 06:43

    Firebase fires two local events for that write operation:

    1. it immediately fires a child_added event with the local timestamp (corrected for your expected offset to the server)
    2. it later fires a child_changed event with the actual timestamp as the server specified it.

    So you can solve the problem by listening for both events:

    var fb = new Firebase('https://xxxxxxxxxxx.firebaseio.com/test');
    
    var query = fb.limitToLast(1);
    query.on('child_added', function(snap) {
        console.log('key', snap.key());
        console.log('val', snap.val());
    });
    query.on('child_changed', function(snap) {
        console.log('key', snap.key());
        console.log('val', snap.val());
    });
    
    fb.push({
        date_now: Firebase.ServerValue.TIMESTAMP
    });
    

    In general it is recommended to handle all child_* events and not just child_added. There may be more reasons why the server has to update or remove the value, to correct for the local event.

    If you prefer having a single callback/event handler, you can also listen for the value event:

    var query = fb.limitToLast(1);
    query.on('value', function(snap) {
        snap.forEach(function(child) {
            console.log('key', child.key());
            console.log('val', child.val());
        });
    });
    

    You'll note the use of forEach() in the callback.

提交回复
热议问题