[D3] Better Code Organization with selection.call() with D3 v4
Most of D3’s native selection APIs also return the selection (or a new selection), to enable multiple method calls to be chained together. Since the code you write isn’t on the selection prototype, chaining your methods would take some extra work. selection.call()
will call any function reference you give it, providing the selection as the first parameter, and then it returns the selection for you to ensure chaining is supported.
var scores = [ { name: 'Alice', score: 96 }, { name: 'Billy', score: 83 }, { name: 'Cindy', score: 91 }, { name: 'David', score: 96 }, { name: 'Emily', score: 88 } ]; var bar = d3.select('.chart') .append('svg') .attr('width', 225) .attr('height', 300) .selectAll('g') .data(scores) .enter() .append('g') .attr('transform', (d, i) => 'translate(0, ' + i * 33 + ')'); function scaleBar (selection, scale) { selection.style('transform', 'scaleX(' + scale + ')'); } function setFill (selection, color) { selection.style('fill', color); } function fade (selection, opacity) { selection.style('fill-opacity', opacity); } bar.append('rect') .style('width', d => d.score) .attr('class', 'bar') .on('mouseover', function (d, i, elements) { d3.select(this) .call(scaleBar, 2) .call(setFill, 'orange'); d3.selectAll(elements) .filter(':not(:hover)') .call(fade, 0.5); }) .on('mouseout', function (d, i, elements) { d3.select(this) .call(scaleBar, 1) .call(setFill, 'lightgreen'); d3.selectAll(elements) .call(fade, 1); }); bar.append('text') .attr('y', 20) .text(function (d) { return d.name; });
分类:
D3
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2016-08-07 [React] Higher Order Components (replaces Mixins)
2014-08-07 [Backbone] Parse JSON on Collection
2014-08-07 [Backbone] Parse not formatted JSON code
2014-08-07 [Backbone]8. Level 7: Router and history