0

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)?

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
tonitone120
  • 1,920
  • 3
  • 8
  • 25

1 Answers1

1

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.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441