Created
November 27, 2012 06:04
-
-
Save dandavison/4152640 to your computer and use it in GitHub Desktop.
d3 reusable chart: coffeescript
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
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) |
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.
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
A coffeescript version of http://bost.ocks.org/mike/chart/
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 chartselection.call(chart.draw)
instead ofselection.call(chart)