2

I need to call a function with the same parameter's values to refresh a ChartJs with a new daterange.

The _reportDateStart and _reportDateEnd are updated outside of the function, so I need to recall the function so the chart is updated with the new data.

The script is:

var _reportDateStart;
var _reportDateEnd;

var _loadChart = function (chartLabel, queryMetrics, queryDimensions) {}

The call is made like this:

_loadChart("Visits", "ga:sessions", "ga:date,ga:nthDay");

But can also be:

 _loadChart("Users", "ga:users", "ga:date,ga:nthDay");
Patrick
  • 2,995
  • 14
  • 64
  • 125

4 Answers4

2

Declare globally accessible variables and assign the parameters on every call that way you can call the function with those variables again: Example:

var param1,param2,param3;
var _loadChart = function(a, b, c){
    param1 = a;
    param2 = b;
    param3 = c;
    //rest of the code.
};

function callTheFunctionAgain(){
    _loadChart(a, b, c);
}
_loadChart("Visits", "ga:sessions", "ga:date,ga:nthDay");
callTheFunctionAgain();
Shakti Phartiyal
  • 6,156
  • 3
  • 25
  • 46
  • Hi thanks! Is there a way to just call _loadChart again without setting the parameters outside of the function? – Patrick Mar 20 '17 at 17:27
  • No I don't think so, you need to store the parameters somewhere if you plan to call the function with those parameters again. If you are planning to call the function from within itself again, then in that case no need to store the variables anywhere simply call _loadChart(chartLabel, queryMetrics, queryDimensions); But that is applicable only if you call it from within itself. – Shakti Phartiyal Mar 20 '17 at 17:29
1

to do this you can create a new function with bound param as you wish like this var _loadChartBounded = _loadChart.bind(null, "Visits", "ga:sessions", "ga:date,ga:nthDay")

then every time you call _loadChartBounded() it will get the same param

0

We already have global variables and .bind()
I will throw in another solution which uses a closure

For an explanation on how these work, head over to this question and its excellent answers:
How do JavaScript closures work?

// This is only an example.
// Please change the variable names to something more meaningful :)

var _loadContent = (function() {
  var _a, _b, _c;

  return function(a, b, c) {
    if (typeof _a === "undefined") {
      _a = a;
      _b = b;
      _c = c;
    }

    console.log(_a, _b, _c);
  }
}());

_loadContent(1, 2, 3);
_loadContent(4, 5, 6);
_loadContent();
Community
  • 1
  • 1
Andreas
  • 21,535
  • 7
  • 47
  • 56
0

For those arriving in the now (15 Jun 2020), here's the most robust way to call a function from within it:

let fn = (a, b, c) => {
    /* fn's content */
    fn(...arguments);
}

This works great if you don't know what the parameters will be (user input), or simply do not want to have to change the parameters in multiple places when refactoring the code.

Reference