简体   繁体   中英

In Firebase's Realtime Database, how can I pass my own arguments to an event listener's callback?

Below is pseudo-code for the way you write a listener for a Realtime Database event.

function callbackA(snapshot) {
  console.log(snapshot.val());
}

route.on('value', callbackA);

Now imagine I want to pass some arguments to callbackA so that callbackA might look like this:

function callbackA(snapshot, myParam1, myParam2) {
  console.log(snapshot.val());
  console.log(myParam1);
  console.log(myParam2);
}

How can I do this (without ruining the first arg that firebase automatically provides for us)?

You can't change the arguments that the Firebase SDK passes to the callback function. It will always attempt to pass exactly one argument: the snapshot.

Instead, you could simply provide the values as variables within the scope of the callback, and access them directly.

const myParam1 = ...
const myParam2 = ...

function callbackA(snapshot) {
  console.log(snapshot.val());
  console.log(myParam1)
  console.log(myParam2)
}

Or you can use function currying to create a new function to pass as the callback. It might go something like this (this untested code - use your best judgement here):

function callbackA(myParam1, myParam2) {
    return function(snapshot) {
        console.log(snapshot.val());
    }
}

const callbackB = callbackA("value-for-myparam1", "value-for-myparam2")
route.on('value', callbackB);

You will obviously need to know the values for the params before you call the Firebase SDK.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM