Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unlink listener for parent does it applied to children in Firebase

I am using firebase to synch data in a real time app. After some treatment, I want to unlink all listeners added. So I put

myRef.off();

But I discover that some listeners are still attached.

My question is: when you put listeners to off for a parent node does it propagate to children or should I put off each level separately?

like image 552
iouhammi Avatar asked Jun 16 '15 18:06

iouhammi


People also ask

How does Firebase listener work?

Firebase utilizes listeners to watch for changes in a specified node. It is similar to an event handler in the sense that a code is triggered based on a certain circumstance. In our case, whenever changes in that node's data occur, the listener automatically provides the application updated data, called a snapshot.

Can anyone access my Firebase database?

By default, your rules do not allow anyone access to your database. This is to protect your database from abuse until you have time to customize your rules or set up authentication. Describes if and when data is allowed to be read by users.


2 Answers

Let's 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');

The output:

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

So after calling off on the parent listener, the child listener still fires ("3"). But if we get the same child and call off, it doesn't for anymore ("4").

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

Conclusion: off() doesn't remove listeners from child nodes.

like image 173
Frank van Puffelen Avatar answered Oct 22 '22 19:10

Frank van Puffelen


Detach a callback previously attached with on(). Note that if on() 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 correct you have to call off() for every on() you did.

like image 33
André Kool Avatar answered Oct 22 '22 18:10

André Kool