Writing Components in D3

by ramnathv

HTML

<div id="rating">
    <div class='title'>
      Clickable Rating
    </div>  
</div>

CSS

.star{
  color: #ccc;
  cursor: pointer;
}
.star.highlight{
  color: darkgreen;
}
.star.highlighted{
  color: darkgreen;
}

CoffeeScript

Stars = ->
  exports = (selection) ->
    selection.each (data) ->
        sel = d3.select(@)
        stars = sel.selectAll(".star").data(data)
        stars.enter().append("span")
          .classed("star", true)
          .style("visibility", "hidden")
        label = sel.selectAll("label").data([data])
        label.enter().append("label")
        stars
         .html("&#9733")
         .transition()
         .duration(100)
         .delay((d, i) -> i*100)
         .style("visibility", "visible")
            
        stars.on "click", (d, i) ->
          stars.classed("highlighted", false)
          stars
            .filter((d2, i2) -> i2 <= i)
            .classed("highlighted", true)
          label.text(i + i)
            
        stars.on "mouseover", (d, i) ->
          console.log(i)
          stars
            .filter((d2, i2) -> i2 <= i)
            .classed("highlight", true)
        stars.on "mouseout", (d, i) ->
          stars.classed("highlight", false)
        return stars
            
            
        
d3.select("#rating")
  .datum(d3.range(10))
  .call(Stars())