2014-12-09 2 views
1

D3을 사용하는 자바 스크립트 코드를 리팩터링하려고하는데 문제가 발생했습니다. 먼저 질문을하는 것보다 코드를 게시 할 것입니다.필터 콜백에 추가 인수 전달 D3 & javascript

add_link:function(e){ 
    // Get the source and target nodes 
    var sourceNode = this.graph.nodes.filter(this.is_source_node)[0]; 
} 

wraping 함수에서 e 인수를 자동으로 D3에 3 개의 인수를받는 콜백 함수에 전달해야합니다. 콜백 함수는 다음과 같습니다.

is_source_node:function(n){ 
    return n.node.id === e.source.node.id; 
} 

나는 자바 스크립트 코어를 사용하거나 자바 스크립트 코어를 사용하여이를 수행하는 몇 가지 기술이 있어야한다고 생각했다.

답변

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 값으로 원래의 함수를 호출하는 함수를 (반환) 여기에 문제가되지 않습니다. 그리고 당신이 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"
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> 
 
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>