我正在尝试重构使用D3的javascript代码,我遇到了一个问题。 我将首先发布代码而不是问问题。
add_link:function(e){
// Get the source and target nodes
var sourceNode = this.graph.nodes.filter(this.is_source_node)[0];
}
我需要将包装函数中的e参数传递给回调函数,该函数自动通过D3获取3个参数。 回调函数看起来像这样。
is_source_node:function(n){
return n.node.id === e.source.node.id;
}
我认为应该有一些技术可以使用javascript核心来完成,或者也许是一个辅助函数来做到这一点。
答案 0 :(得分:2)
你可以"咖喱"该论点来自Function#bind
:
add_link:function(e){
// Get the source and target nodes
var sourceNode = this.graph.nodes.filter(this.is_source_node.bind(this, e))[0];
// Change is here ------------------------------------------^^^^^^^^^^^^^
}
然后:
// Change --------------vvv
is_source_node:function(e, n){
return n.node.id === e.source.node.id;
}
Function#bind
返回一个函数,该函数在调用时将调用具有特定this
值的原始函数(此处并不重要)以及您提供的任何其他参数{{1}然后是实际调用它的参数。
一个更简单的例子可能更清楚:
bind

function foo(a, b) {
snippet.log("a is " + a + ", b is " + b);
}
foo(1, 2); // "a is 1, b is 2" as you'd expect
// Create a function that will call foo with 'first'
var f= foo.bind(null, 'first');
// Call it, passing in an argument
f('second'); // "a is first, b is second"