Skip to content

Instantly share code, notes, and snippets.

@dandavison
Created November 27, 2012 06:04
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dandavison/4152640 to your computer and use it in GitHub Desktop.
Save dandavison/4152640 to your computer and use it in GitHub Desktop.
d3 reusable chart: coffeescript
class BaseChart
constructor: ->
@_width = 720
@_height = 80
draw: (selection) =>
me = @
selection.each( (d, i) -> me._draw(this, d, i) )
_draw: (elem, d, i) ->
throw "Not Implemented"
width: (value) ->
if not arguments.length
return @_width
@_width = value
@
height: (value) ->
if not arguments.length
return @_height
@_height = value
@
class MyChart extends BaseChart
_draw: (elem, d, i) ->
# generate chart here; `d` is the data and `elem` is the element
chart = new MyChart()
chart.width(800).height(120)
d3.select('body').datum(data).call(chart.draw)
@bewest
Copy link

bewest commented Dec 16, 2012

Looks nice! Use of new doesn't seem problematic. Could you include the method for selecting?

chart = new MyChart( );
chart.width(800).height(120)
       .render(data);

I like the idea of a coffee script classes providing factory methods to set up d3 for more common usage.

@wprater
Copy link

wprater commented May 31, 2013

Forked the gist to fix the two issues that you had with your implementation. Although, I think it's simpler to use the method that you presented. Hope this helps. Have you been using your Coffee version in your projects?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment