Understanding D3 Selections
by ramnathv
HTML
<script src="//d3js.org/d3.v3.min.js"></script>
<div id="chart"></div>
<button id="update">Update</button>
CoffeeScript
###
The objective here is to gain a more in-depth understanding of D3 selections. The authoritative article for this is
http://bost.ocks.org/mike/selection/
The motivation comes from a weird observation in rcstatebin where updating using the following two selections resulted in different behaviors on update.
svg.selectAll('.cell').select('rect.state')
svg.selectAll('.cell rect.state')
I figured out that updating the data was not updating the data underlying rect.state. Adding a statement as simple as
svg.selectAll(".cell").select("rect.state").data() made the second selection work. I need to get into the heart of data binding to prevent errors like this.
###
data = ['A', 'B', 'C', 'D']
chart = d3.select('#chart')
li = chart.selectAll('li')
.data(data).enter()
.append('li')
li.append('span')
.text((d) -> d)
update = ->
chart.selectAll("li").select("span")
.style 'color', (d, i) ->
if d is 'B' then 'red' else 'green'
d3.select("#update").on "click", update