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.
Can I execute
off()
directly in theon()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With