ehacinom
ehacinom

Reputation: 8894

Javascript: calling function within D3 from another file

I want to rewrite several functions, relating to one of the layouts, in the d3.js script. When I cut-and-paste these functions into separate files and load them after d3.js, visualizations no longer work, because internal functions call internal functions of d3.js.

d3.js:

!function() {
  var d3 = { version: "3.5.17" };
  function d3_funct() { return d3; } // this function is called in the other file
}();

chord.js:

d3.svg.chord() = function() {
  var funct = d3_funct; // doesn't work
};

Question:

How would I use the above function, d3_funct, inside my script chord.js, when d3_funct is defined inside an immediately-executed function expression in another file?

Options:

  1. edit d3.js file directly instead of pulling out functions to rewrite :(
  2. Rename the enclosing d3 function and use jQuery to load it into chord.js.

Am I missing something?

Upvotes: 1

Views: 1453

Answers (1)

Matthew Herbst
Matthew Herbst

Reputation: 32003

So, your order of execution should be:

  1. Load d3.js
  2. Load your custom modifications
  3. Load the rest of your code

Your modifications file should look something like:

function myBetterD3Funct () { ... }
d3.d3_funct = myBetterD3Funct;

The above would be by far the best option. It's extremely clear what you're doing and doesn't require you to modify the d3.js file every time you download the newest version (thus allowing you to use a d3 cdn to serve d3.js to your users).

Another option exists if you don't want to override the d3 global function itself. I warn you that the below may not work for all cases depending on how complex your myBetterD3Funct and what it needs access to within d3.

function myBetterD3Funct () { ... }
myBetterD3Funct.apply(d3);

What this is doing is setting the scope of your function (at runtime) to the global d3 object. This would allow it to reference top-level properties within the global d3 object using this. As noted in a comment below, many functions and variables within the code are written to be private, and so you cannot access them in any way (save for modifying the source code).

Upvotes: 1

Related Questions