Say I have the following:
var firebaseARef = new Firebase("http://this.is.my/firebase/url/A/reference")
var firebaseBRef = new Firebase("http://this.is.my/firebase/url/B/reference")
When I define my .on()
functions, I'd like to specify a single handler, and then do all of the handling in one place in my code, rather than having to define the functions inline with the .on()
definition. To illustrate:
var handleAllFirebaseStuff = function(dataSnapshot){
var name = dataSnapshot.name(); //PROBLEM HERE: returns "reference", no way to distinguish!
switch(name){
case "http://this.is.my/firebase/url/A/reference": //How do I get this full reference from dataSnapshot?
/* do stuff for A reference */
case "http://this.is.my/firebase/url/B/reference": //How do I get this full reference from dataSnapshot?
/* do stuff for B reference */
default:
break;
}
}
firebaseARef.on('value', handleAllFirebaseStuff);
firebaseBRef.on('value', handleAllFirebaseStuff);
The problem is dataSnapshot.name()
will only return "reference"
in both cases, making it impossible to distinguish between the two references in the switch/case statement!
I'm certain that dataSnapshot
contains this information somewhere, but I have yet to uncover it in any convenient fashion. Exploring the dataSnapshot
object in the console, I find that there is an object buried within called path
that contains (among other things) an array, using the example above, that would contain ["firebase", "url", "A", "reference"]
, but there is no easy way to access it.
If I had access to that array, I could rebuild the URL or find a more convenient way to handle the switch/case statement. I think a full string of the reference would be more appropriate as an easily accessible value from dataSnapshot
.
To get back from a Snapshot
to the full URL, you do:
snapshot.ref().toString()
The toString
part is somewhat counter-intuitive. I often find myself having to test it, to see if that's indeed the way to go.
hint It would be nice if there was also a more explicit getUrl
method hint
With recent SDK versions ref
is no longer a function, so you'll have to use:
snapshot.ref.toString();
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