简体   繁体   English

Javascript:从另一个文件调用 D3 中的函数

[英]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.我想在 d3.js 脚本中重写几个与布局之一相关的函数。 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 之后加载它们时,可视化不再起作用,因为内部函数调用 d3.js 的内部函数。

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:和弦.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?d3_funct在另一个文件中的立即执行的函数表达式中定义时,我将如何在我的脚本 chord.js 中使用上述函数d3_funct

Options:选项:

  1. edit d3.js file directly instead of pulling out functions to rewrite :(直接编辑 d3.js 文件而不是拉出函数来重写:(
  2. Rename the enclosing d3 function and use jQuery to load it into chord.js.重命名封闭的 d3 函数并使用 jQuery 将其加载到 chord.js 中。

Am I missing something?我错过了什么吗?

So, your order of execution should be:所以,你的执行顺序应该是:

  1. Load d3.js加载 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).您在做什么非常清楚,并且不需要您每次下载最新版本时都修改 d3.js 文件(从而允许您使用 d3 cdn 为您的用户提供 d3.js 服务)。

Another option exists if you don't want to override the d3 global function itself.如果您不想覆盖 d3 全局函数本身,则存在另一个选项。 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 .我警告您,以下内容可能不适用于所有情况,具体取决于您的myBetterD3Funct复杂myBetterD3Funct以及它需要在d3访问的内容。

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

What this is doing is setting the scope of your function (at runtime) to the global d3 object.这样做是将函数的范围(在运行时)设置为全局 d3 对象。 This would allow it to reference top-level properties within the global d3 object using this .这将允许它使用this引用全局d3对象中的顶级属性。 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).正如下面的评论中所指出的,代码中的许多函数和变量都被编写为 private ,因此您无法以任何方式访问它们(除了修改源代码)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM