如何在JavaScript中将额外变量传递到Firebase Promise的回调函数?

3
我们正在尝试将额外的变量传递到Firebase .ON promise的回调函数中。我们查看了SO上数十篇关于如何将静态变量传递给.ON方法回调函数的帖子,但每个版本都会为我们抛出data.val()未定义的错误。
以下是示例代码。我们想为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);

我们认为我们可能能够做类似这样的事情,但我们无法使其变化起作用:
fx_call(data,i) { 
     value = data.val();
     i = i.val(); 
};

或者,看起来我们可以通过 .bind 语句传递我们的值:

fx_call(data,i) { 
     value = data.val();
     i = i.val(); 
}.bind(this, i) # we also tried .bind(null,i) and .bind(i)

但是我们尝试了多个stackoverflow帖子的方法(1,2,3和其他),但都导致了一个data.val()未定义的错误。

我们如何将额外的变量参数传递给我们promise的回调函数?

1个回答

4
我们在SO以外找到了一个答案,所以我们正在请求并回答以将其添加在这里。
您可以使用以下格式的 .bind 语句将变量传递给包括 Firebase promise 回调在内的函数:
 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

你可以在函数的顶部加上var i=5, j=10 - 我一定是错过了问题的要点 - Jaromanda X
@JaromandaX 整数只是用来放置实际变量的占位符。答案已经修订,用 i 显示了这一点。 - Praxiteles
非常感谢您 :) 您也可以这样做:path.on('value',function(data){ ...一些操作 }.bind({something})); - magorich

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接