3

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?

Community
  • 1
  • 1
Praxiteles
  • 5,802
  • 9
  • 47
  • 78

1 Answers1

4

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
Praxiteles
  • 5,802
  • 9
  • 47
  • 78
  • you may as well have `var i=5, j=10` at the top of the function - I must've missed the point of the question – Jaromanda X Jan 29 '17 at 23:53
  • @JaromandaX The integers were just placeholders for where actual variables would go. Answer revised to show that with i. – Praxiteles Jan 30 '17 at 02:51
  • Thanks a lot for this :) you can also do it like this path.on('value',function(data){ ...something }.bind({something})); – magorich Jun 30 '17 at 19:01