私が書いたいくつかの d3 コードを使用して、小さなチャート ライブラリに取り組んでいます。さまざまなユース ケースに合わせてチャートに構成/カスタマイズ オプションを追加してきましたが、イベント ハンドラーの競合に遭遇し続けています。
トランジションは時々私に問題を引き起こしますが、私の質問はそれよりも一般的です. チャート内で一連のイベント ハンドラーを実行するにはどうすればよいですか?
私が使用した 1 つの方法は、ハンドラーのリテラル配列を構築し、リストを反復処理して各ハンドラーを実行することです。
function chart(selection) {
selection.each(function(data) {
// initial config and options, including the handlers array
var margin = {top: 20, right: 20, bottom: 50, left: 40},
...
fadeOnHover = true,
barMouseoutHandlers = [],
barMouseoverHandlers = [];
// create the chart
// an option
if (fadeOnHover) {
barMousemoveHandlers.push(function(d, i) {
selection.selectAll('.bar').filter(function(d, j){return i!=j;})
.transition().duration(100).style('opacity', '.5');
selection.selectAll('.bar').filter(function(d, j){return i==j;})
.transition().duration(100).style('opacity', '1');
});
barMouseoutHandlers.push(function() {
selection.selectAll('.bar').transition().duration(100).style('opacity', '1');
});
}
// other options, which may add handlers
// then at the end of the function, execute all handlers
g.selectAll('.bar')
.on('mouseover', function(d, i) {
barMouseoverHandlers.forEach(function(handler) { handler(d, i); });
})
.on('mouseout', function(d, i) {
barMouseoutHandlers.forEach(function(handler) { handler(d, i); });
});
});
}
これは、チャートにいくつかの機能を追加したときに思いついたものですが、モジュール化されていないか、よく整理されていないことは明らかです。おそらく、これらの断片の一部を個別のオブジェクトに抽出する余地があります。
他にどのようなアプローチがありますか?これについてのご意見をお聞かせいただければ幸いです。