Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use off() directly in on() callback Firebase?

Let's say I have a one and done operation. Like deletes.

var q = ref.child('users').child(targetUserId).child('chat');
q.on('child_added', function(obj) {
  obj.ref().remove();

  //This works right?
  q.off();
}); 

Can I execute off() directly in the on() callback? I don't need to specify eventType correct?

Nothing else to clean up right?

From the docs:
Similarly, if no eventType or callback is specified, all callbacks for the reference will be removed.

like image 226
Dan Kanze Avatar asked Feb 01 '15 18:02

Dan Kanze


1 Answers

Can I execute off() directly in the on() callback?

Yes.

I don't need to specify eventType correct?

Correct. As the docs state, if the eventType is omitted, all callbacks for the reference will be removed.

You can also just chain the .off() method like this rather than calling it inside of the callback:

var q = ref.child('users').child(targetUserId).child('chat');
q.on('child_added', function(obj) {
  obj.ref().remove();
}).off();

As Frank van Puffelen suggests in the comments, you can also use the .once() method in order for the callback to only be executed once:

var q = ref.child('users').child(targetUserId).child('chat');
q.once('child_added', function(obj) {
  obj.ref().remove();
});

The benefit to this approach is that you don't have to worry about inadvertently removing other attached events.

like image 128
Josh Crozier Avatar answered Sep 19 '22 02:09

Josh Crozier