We are trying to pass additional variables into a Firebase .ON promise's callback. We have looked at dozens of posts on SO describing how to pass static variables into callback functions for .ON methods - but each version is throwing a data.val() undefined error for us.
Here is sample code. We want to pass in a value for i:
var path = firebase.database().ref(our_firebase_data_url);
var fx = function fx_call(data) {
value = data.val();
console.log("Here is your passed parameter: " + i); // we want this defined
};
path.on('value', fx);
We thought we might be able to do something like this but we are unable to get variations on this to work:
fx_call(data,i) {
value = data.val();
i = i.val();
};
Alternatively, it looked like we could pass in our values via a .bind statement:
fx_call(data,i) {
value = data.val();
i = i.val();
}.bind(this, i) # we also tried .bind(null,i) and .bind(i)
But every approach we have tried from multiple SO posts (1,2,3 and others) resulted in a data.val() undefined error for us.
How can we pass in additional variable parameters to our promise's callback?
We found an answer outside of SO, so we are asking and answering to add it here.
You can pass variables into functions including Firebase promise callbacks using a .bind statement formatted this way:
fx_call(data,i) {
value = data.val();
i = this.i; # this is how you access the value from the bind
j = this.j;
}.bind( {i: i, j: 10} ) # this is how you pass variables into the callback function...this.i will be whatever value the scope of i was at the time the function was created...this.j in this case will be 10
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