Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass additional variables into a Firebase promise's callback in Javascript?

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?

like image 561
Praxiteles Avatar asked Apr 07 '26 06:04

Praxiteles


1 Answers

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
like image 51
Praxiteles Avatar answered Apr 08 '26 19:04

Praxiteles