[英]Using objects to simplify code in d3.js
I'd like to make code easy to read. 我想使代码易于阅读。 There are too duplicated methods like this.
这样的方法太重复了。
var svg = d3.append('svg').attr(...).attr('...').attr('...').style(...).style(...);
This is a bit difficult to read so I want to simplify code. 这有点难以阅读,所以我想简化代码。
var svg = d3.append('svg').attr({'class','test_class'},{'x','x_value'}).style({'fill','value'},{...});
Any help would be appreciated. 任何帮助,将不胜感激。
D3 version 3.x D3版本3.x
You can do that using D3 v3.x. 您可以使用D3 v3.x来完成。 Check the demo:
查看演示:
var svg = d3.select("body") .append("svg"); var data = [10, 5, 15, 20, 12, 8, 17]; var circles = svg.selectAll(".circle") .data(data) .enter() .append("circle"); circles.attr({ cx: function (d,i) { return 10 + i*40; }, cy: 50, r: function (d) { return d; }, fill: "teal" });
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
D3 version 4.x D3版本4.x
However, this will not work in the new D3 v4.x. 但是,这在新的D3 v4.x中不起作用。 For passing objects like that, you'll need the
selection-multi
: 为了传递这样的对象,您需要
selection-multi
:
<script src="https://d3js.org/d3-selection-multi.v1.min.js"></script>
Besides that, have in mind that you'll have to change: 除此之外,请记住您必须进行以下更改:
attr
must be attrs
attr
必须是attrs
style
must be styles
style
一定是styles
Check the demo using v4.x: 使用v4.x查看演示:
var svg = d3.select("body") .append("svg"); var data = [10, 5, 15, 20, 12, 8, 17]; var circles = svg.selectAll(".circle") .data(data) .enter() .append("circle"); circles.attrs({ cx: function (d,i) { return 10 + i*40; }, cy: 50, r: function (d) { return d; }, fill: "teal" });
<script src="https://d3js.org/d3.v4.min.js"></script> <script src="https://d3js.org/d3-selection-multi.v1.min.js"></script>
PS: your example of simplified code (the second one) is not a valid object (because the key/value pair is separated by comma instead of colon) or a valid array (because there is no square bracket). PS:您的简化代码示例(第二个示例)不是有效的对象(因为键/值对用逗号而不是冒号分隔)或有效的数组(因为没有方括号)。 Thus, it should be:
因此,应为:
.attr({'class': 'test_class', 'x': 'x_value'})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.