You can use selection.call()
to re-use behavior on multiple selections. Here, I've defined a colorable
function which adds a CSS rule and a click behavior to this
, then used selection.call(colorable)
to invoke it on two different selections. There are two things to note: first, the colorable
function is called with the selection as this
. Second, you don't lose the ability to access the selection's data in your setters.
xxxxxxxxxx
<meta charset="utf-8">
<style>
.container > div {
display: inline-block;
width: 80px;
text-align: center;
border: 1px solid black;
padding: 40px 10px;
margin: 10px;
}
</style>
<div class="container" id="top"></div>
<div class="container" id="bottom"></div>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var data = ['red', 'blue', 'green', 'yellow'];
d3.select('#top').selectAll('div')
.data(data).enter()
.append('div')
.html(function(d) { return d; })
.call(colorable);
d3.select('#bottom').selectAll('div')
.data(data.reverse()).enter()
.append('div')
.html(function(d) { return d; })
.call(colorable);
function colorable() {
this.on('click', function(d) {
d3.select(this).style('background-color', d);
}).style('cursor', 'pointer');
}
</script>
https://d3js.org/d3.v3.min.js