Firebase:为什么将Firestore .onSnapshot分配给变量?

时间:2018-10-16 19:18:50

标签: firebase google-cloud-firestore

下面显示了Firestore documentation,作为如何将实时更新侦听器附加到Firestore数据的示例。我的问题是,为什么我需要将侦听器分配给变量?换句话说,我知道有人可能会给变量分配一个诺言,因此可以returnawait.push编辑一个数组,但似乎没有一个适用于实时收听者,除非我遗漏了要点? ...为什么将.onSnapshot分配给var

var doc = db.collection('cities').doc('SF');

var observer = doc.onSnapshot(docSnapshot => {
  console.log(`Received doc snapshot: ${docSnapshot}`);
  // ...
}, err => {
  console.log(`Encountered error: ${err}`);
});

2 个答案:

答案 0 :(得分:2)

这使您以后可以删除观察者。对于您而言,您可以通过致电observer()来退订,这就是为什么我们通常按照detach a listener一节中的名称来称为unsubscribe

答案 1 :(得分:0)

firebase.firestore.CollectionReference firebase.firestore.DocumentReference是调用.onSnapshot方法的必需变量。单个通用muteListener函数可以接收对静音/取消订阅的任何引用。假设您正在收听地址文件:

var shipToLocationDocument = null;

function muteListener(ref){
    return ref.onSnapshot(() => {});
}

shipToLocationDocumentListener = function () {
    return shipToLocationDocumentRef.onSnapshot(function (shipToLocationDocumentSnapshot) {
        //callback function to fire
        shipToLocationDocumentStateHandler(shipToLocationDocumentSnapshot);
    }, function(error) {
        console.log("shipToLocationDocumentSnapshot error " + error.message);
    });
};
//call the function
shipToLocationDocumentListener();

//callback function
function shipToLocationDocumentStateHandler(shipToLocationDocumentSnapshot){
    if(shipToLocationDocumentSnapshot.exists){
        shipToLocationDocument = shipToLocationDocumentSnapshot;
        displayShipToLocation(shoppingCartDocument.data().shipTo); //actually we have all the info here already
    } else {
        shipToLocationDocument == null;
    }
}