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.
Last active
June 1, 2016 19:35
-
-
Save benkimball/19f0c25ffda89801ffe162be05a6a53e to your computer and use it in GitHub Desktop.
Using d3's selection.call()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
height: 300 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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