FairyQueen
FairyQueen

Reputation: 2373

How to pass an arg to the function inside lodash's once function?

So I am calling a function that calls lodash's once function:

  if (isPageTwo) {
    sendSegmentData(sendEnhancedTrackEvent);
  }

And I have the functions defined here:

const pageTwoSegmentEvent = (sendEnhancedTrackEvent) => {
  const enhanceableData = {
    name: 'Page loaded',
    properties: {
      ...defaultProps,
      cid: getCid(),
      epid: getEpid(),
      name: 'ReviewExperienceModernDoubleStep'
    }
  };
  sendEnhancedTrackEvent(enhanceableData);
}
const sendSegmentData = (sendEnhancedTrackEvent) => {
  once(() => {
    pageTwoSegmentEvent(sendEnhancedTrackEvent);
  });
}

I am trying to pass the sendEnhancedTrackEvent callback function to the pageTwoSegmentEvent function but I guess the way I'm trying to pass it through the once function pageTwoSegmentEvent never gets called. Does anyone know how to do this?

Upvotes: 1

Views: 634

Answers (2)

Ori Drori
Ori Drori

Reputation: 191976

The _.once() method takes a function (func), and returns a function that invokes the wrapped function (func) a single time. According to the docs:

The func is invoked with the this binding and arguments of the created function.

Which means that whatever arguments you pass to the new function, will be passed to the wrapped func.

In your case:

  1. sendSegmentData has the sendEnhancedTrackEvent param
  2. When sendSegmentData is invoked, it calls once(() => { pageTwoSegmentEvent(sendEnhancedTrackEvent); });, which creates a new function. The new function is not returned or called.

To create sendSegmentData, call once on pageTwoSegmentEvent directly. This will return a new function, that will pass whatever arguments in gets to pageTwoSegmentEvent.

Example:

const { once } = _

const pageTwoSegmentEvent = (sendEnhancedTrackEvent) => console.log(sendEnhancedTrackEvent)

const sendSegmentData = once(pageTwoSegmentEvent)

sendSegmentData('1')

sendSegmentData('2')

sendSegmentData('3')
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

Upvotes: 1

Victor P
Victor P

Reputation: 1612

_.once returns the function that you need to invoke. No matter how many times you call this function it will only be invoked once.

Assuming once is an alias to _.once, try changing it to this:

const sendSegmentData = once((sendEnhancedTrackEvent) => {
    pageTwoSegmentEvent(sendEnhancedTrackEvent);
});

...

// somewhere else call it
sendSegmentData(theSegmentedData);

Upvotes: 0

Related Questions