オレンジ :
私は(すなわち、異なる呼び出し異なったデータをもとに、「スタイル」の矩形の複数の関数を作成したい.attr()
か.style()
の機能、さらにはデータに基づいて他の要素を追加します)。
私が使用するために管理し.call(myDecorator)
、別の関数にスタイリングを派遣するが、ここで私は少しは打っています。rectDecorator
私はに基づいて異なるサブ選択を呼び出したいですd.type
。現時点では(.style('fill'...).style(...).style(...)
)が示す長方形を飾るために、それらの可能な方法のひとつが、理想的に、私はに基づいて異なる連鎖コマンドに「ブランチ」したいと思いますd.type
。私はそれを達成できるか任意のアイデア?
function rectDecorator(selection) {
// call different selection.xyz functions to style rect differently based on `d.type`
return selection
.style('fill', function(d) {
return d.color;
})
.style('fill-opacity', 1)
.style('stroke-width', 0);
}
d3.select('svg')
.selectAll('g')
.data(data)
.join(
enter => enter
.append('g')
.append('rect')
.attr('x', ...)
.attr('y', ...)
.attr('height', 20)
.attr('width', 40)
.call(rectDecorator)
update => update(),
exit => exit.remove()
高積雲:
ある時点で、あなたは特定のデコレータを見つけるために、各要素の個々のタイプをチェックするために選択を反復処理する必要があります、が、これまで複数の可能なソリューションがあります。あなたは、設定することができMap
、それらに対応するデコレータにタイプをマッピングすることによりを。
const decorators = new Map([
["type1", selection => selection.attr("attr1", "...")],
["type2", selection => selection.attr("attr2", "...")]
]);
その後、あなたは簡単に選択することでループが使用可能.each()
とデータムのに基づいてマップから、適切なデコレータを取得type
プロパティを:
.each(function(d) {
d3.select(this).call(decorators.get(d.type));
})
デモ作業のために次のコードを見てみましょう:
const decorators = new Map([
["red", selection => selection.attr("fill", "red")],
["green", selection => selection.attr("fill", "none").attr("stroke", "green")]
]);
const data = [{ type: "green" }, { type: "red" }];
d3.select('body').append("svg")
.selectAll('g')
.data(data)
.join(
enter => enter
.append('g')
.append('rect')
.attr('x', (_, i) => i * 50 + 50)
.attr('y', 50)
.attr('height', 20)
.attr('width', 40)
.each(function(d) {
d3.select(this).call(decorators.get(d.type));
})
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.15.0/d3.js"></script>