Unlink listener for parent applies to children in Firebase

I am using firebase to sync data in a real time application. After some treatment, I want to disable adding all listeners. So I put

myRef.off();

      

But I found that some listeners are still connected.

My question is, when you disable listeners for the parent node, does it propagate to children or should I defer each level separately?

+3


source to share


3 answers


Try it.

ref.on("value", function(snapshot) { 
  console.log("parent: "+JSON.stringify(snapshot.val()));
});
ref.child("child").on("value", function(snapshot) { 
  console.log("child: "+JSON.stringify(snapshot.val()));
});
ref.set('1');
ref.child('child').set('2');
ref.off();
ref.child('child').set('3');
ref.child('child').off();
ref.set('4');

      

Output:

parent: "1"
child: "2"
parent: {"child":"2"}
child: "3"

      



So, after being called off

on the parent listener, the child listener still fires ( "3"

). But if we get the same child and name it off

, it will no longer be ( "4"

).

JSBin: http://jsbin.com/wutaza/edit?js,console

Conclusion: off () does not remove listeners from child nodes.

+6


source


Disconnect the callback previously connected using the () function. Note that if the on () function was called multiple times with the same eventType and callback, the callback will be called multiple times for each event, and off () must be called multiple times to remove the callback.

This comes from the firebase docs on the off () method ( link ).



So, if I read this correctly, you need to undo () for each of the () you did.

+1


source


Thanks to the posts in this thread, I was able to figure out how to stop my callbacks that kept firing after they were initially called for the intended Firebase calls they were passed to. This unexpected callback even happened when I was updating directly in the console.

I ended up with the following solution to disable listeners after the callback has been executed:

var queryRef = someItemRef.limitToLast(1);

queryRef.on('child_added', function (data) {

    queryRef.off();
    onAddSomeItemReadyFunc(data);
});

      

For me, understanding the logic of the listener and avoiding "fraudulent callbacks" was the more challenging aspect of working with the Firebase database. But we are here :)

@Frank van Puffelen, thanks again for the good notes and examples to help keep us Firebase client developers back on track!

0


source







All Articles