Skip to content

Instantly share code, notes, and snippets.

Created November 27, 2012 06:04
Show Gist options
  • 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()
Copy link

A coffeescript version of

This uses a prototype-based "class", which coffeescript supports with special syntax. One consequence is that the API differs from the original:

  • new is used to instantiate the chart
  • instead of

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( );

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

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