0

I have spend a lot of time trying to find a title that explain my question, but not easy. Feel free to suggest.

Code is as follow: I am creating annotation for my chart using google visualisation. The annotation column uses a custom function. This is allowed by google, and the function will received 2 parameters: dt and row. The question is: what should (dt, row, i) in the below be so that I get the default dt, row that the function normally receives and my additional parameter i?

view = new google.visualization.DataView(chartData);
var arr = [0];

for (var i = 1; i < chartData.getNumberOfColumns() ; i++) 
{
    arr.push(i);
    arr.push({role: "annotation", type: "string", calc: (function (dt, row,i)  {
        if (typeof (dt.getValue(row,i)) == "number" && dt.getValue(row,i) == 0) 
        {
            return ""; 
        }
        else 
        { 
            return dt.getValue(row, i).toString; 
        }
    })(dt, row, i)
});
}

view.setColumns(arr);
chartData = view.toDataTable();
3
  • can you use jQuery ?? Commented Jan 31, 2014 at 13:08
  • Sure. How would I use jQuerry to solve this? Commented Jan 31, 2014 at 14:28
  • A title that I feel describes better your question would be; Inject additional parameters into a JavaScript callback function Commented Jan 31, 2014 at 16:04

2 Answers 2

2

I don't know if i got it right, but you can probably use a higher order function for that:

var createCalc = function(i){
    return function(dt, row){
        if (typeof (dt.getValue(row,i)) == "number" && evs == 0) { return ""; }
        else { return dt.getValue(row, i).toString; }
    };
}

...
arr.push({role: "annotation", type: "string", calc: createCalc(i)});
Sign up to request clarification or add additional context in comments.

Comments

1

lets say you have a function createCalc which receives two parameters dt and row from the callback and you want to add your additional parameter i to it. Create a function,

function createCalc(i, dt, row) {
  //functin code
}

and pass it as,

arr.push({role: "annotation", type: "string", calc: createCalc.bind(null, i)});

bind will return a new function adding parameters to it. first argument, i have passed is null, it is actually will be assigned to this variable, pass appropriate value if u use this in your function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.