Skip to content

Instantly share code, notes, and snippets.

@benkimball
Last active June 1, 2016 19:35
Show Gist options
  • Save benkimball/19f0c25ffda89801ffe162be05a6a53e to your computer and use it in GitHub Desktop.
Save benkimball/19f0c25ffda89801ffe162be05a6a53e to your computer and use it in GitHub Desktop.
Using d3's selection.call()
height: 300

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.

<!DOCTYPE html>
<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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment