Patrick
Patrick

Reputation: 2781

Recall a function with the same parameters values with javascript

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");

Upvotes: 2

Views: 1577

Answers (4)

user12944748
user12944748

Reputation:

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

Upvotes: 0

Andreas
Andreas

Reputation: 21881

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();

Upvotes: 0

Nguyễn Hòang
Nguyễn Hòang

Reputation: 11

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

Upvotes: 1

Shakti Phartiyal
Shakti Phartiyal

Reputation: 6254

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();

Upvotes: 2

Related Questions