[英]Inject additional parameters into a JavaScript callback function
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.
这是谷歌允许的,该功能将收到2个参数:dt和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?
问题是:下面应该是什么(dt,row,i),以便我得到默认的dt,函数通常接收的行和我的附加参数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();
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)});
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. 假设您有一个函数
createCalc
,它从回调中接收两个参数dt和row ,并且您想要将其他参数i添加到它。 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. bind
将返回一个向其添加参数的新函数。 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. 第一个参数,我传递的是
null
,它实际上将被赋值给this
变量,如果你在你的函数中使用this
,则传递适当的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.