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.
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.
-
4
If you're turning it on and off again like that, you may consider using
once
instead. – Frank van Puffelen Commented Feb 1, 2015 at 19:29 -
@FrankvanPuffelen I was trying to use
once()
on a slightly different version of the example above -q.endAt(estimatedServerTimeMs-5000).once(...)
- but theremove()
would only delete a single record (the first one in the matching set). Changingonce
toon
would delete all of the matching records. Any idea why that might be? – Dan Kanze Commented Feb 1, 2015 at 20:12 -
2
When using
once
Firebase will only fire a single event. So in case ofchild_added
it will only fire for a single child (no matter how many children match the query). For your original question that is precisely what you need. But indeed for the use-case in your ment, stick toon('child_added'
andoff
it on the right condition or alternativelyonce('value'
and thenforEach
over the children in the snapshot. – Frank van Puffelen Commented Feb 1, 2015 at 20:55
1 Answer
Reset to default 5Can 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 ments, 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.