javascript - 使用闭包将配置绑定(bind)到函数

标签 javascript d3.js

我正在阅读this tutorial关于d3中可重用的图表,在第一个“配置”部分,作者描述了两种制作图表功能的方法:

// Method 1
function chart(config) {
  // generate chart here, using `config.width` and `config.height`
}

// Method 2
function chart(config) {
  return function() {
    // generate chart here, using `config.width` and `config.height`
  };
}

他建议使用第二种方法而不是第一种,因为

However, the caller must then manage both the chart function (assuming you have multiple types of charts to pick from) and the configuration object. To bind the chart configuration to the chart function, we need a closure.

不过我不明白这个解释。方法2相对于第一种方法有什么优点?

最佳答案

这是关于管理信息的。在第一种情况下,如果您想更改图表的配置,调用者必须记住 config 必须传递给 chart:

chart(config);
config.xy = 42;
// update the chart, calling chart again
chart(config);

现在,如果有多个可能不同的图表(因此有不同的图表函数,例如 barchartlinechart 等),调用者必须记住哪个配置传递给哪个函数。

如果图表的“类型”能够以某种方式自包含,那就更容易了。在第二个示例中,您返回对函数的引用,该函数知道如何更新您刚刚创建的图表。因此,您可以在不知道图表是由哪个函数创建的情况下更新图表:

var myChart = chart(config);
config.xy = 42;
// update the chart
myChart();

这似乎是 D3 使用的方法,但您也可以使用面向对象的方法,即创建一个适当的 Chart 构造函数,该函数封装了渲染和更新图表的逻辑。

关于javascript - 使用闭包将配置绑定(bind)到函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12664575/

相关文章:

javascript - 将动态工具提示添加到streamgraph d3.js

javascript - 根据百分比设置JWPlayer Audio Player的样式和大小

javascript - 在模板 DJANGO 中呈现 JSON

javascript - 从 JSON 数组显示 D3 中的坐标

javascript - 检查 d3 函数的参数值

javascript - 使用新数据更新 D3 流图

javascript - 绑定(bind)到子项的数据不会用新数据更新

javascript - 在php中正确显示 map infoWindow

javascript - 使用 Canvas2image 将 HTML 转换为 PNG,然后将 PNG 转换为 BMP

javascript - Angular 5 ng-bootstrap 类型 'ElementRef' 不是通用错误