Reputation: 6454
Afraid I'm making a simple error in in how I convert this JavaScript to CoffeeScript within a class
In this original example of a world map we have a function :
var quantize = d3.scale.quantize()
.domain([0, .15])
.range(d3.range(9).map(function(i) { return "q" + i + "-9"; }));
This is then called when the map is rendered:
.attr("class", function(d) { return quantize(rateById.get(d.id)); })
And we are left with something like class="q8-9
which is what we want.
Converting this to CoffeeScript I have:
quantize: ->
d3.scale.quantize()
.domain([0, .15])
.range(d3.range(9).map((i) -> "q" + i + "-9" ))
Which I then call like this:
.attr("class", (d) => @quantize(rateById.get(d.id)) )
However this does't return a value, rather it returns the scale function, leaving me with this:
class="function scale(x) { return range[Math.max(0, Math.min(i, Math.floor(kx * (x - x0))))]; }"
I'm sure I'm doing something very simple wrong but can't figure it out. Can you help?
Upvotes: 3
Views: 1500
Reputation: 19480
Instead of
quantize: ->
d3.scale.quantize()
.domain([0, .15])
.range(d3.range(9).map((i) -> "q" + i + "-9" ))
you want
quantize :
d3.scale.quantize()
.domain([0, .15])
.range(d3.range(9).map((i) -> "q" + i + "-9" ))
->
is used when you are defining functions but here you are just calling a function (it just happens to return a function) so its similar to its JavaScript counterpart.
Note: Judging by the fact that you had : ->
to begin with and @quantize
which translates to this.quantize
, it looks like you are storing quantize
in an object which is great, and is what the code above assumes. If your code is actually more like the original example you linked to where quantize is just a variable, then you will want quantize = d3...
and quantize(rateId.get(d.id))
(without the @
).
The "Try CoffeeScript" link at the top of the CoffeeScript site lets you write CoffeeScript and it'll translate to JavaScript as you go which is a great way to learn and understand what gets translated into what. There are also plugins for browsers available that do this.
Upvotes: 3
Reputation: 20554
In your Javascript Code, quantize contains a value:
var quantize = d3.scale.quantize()
.domain([0, .15])
.range(d3.range(9).map(function(i) { return "q" + i + "-9"; }));
But in your CoffeeScript version, quantize is a function:
quantize: ->
d3.scale.quantize()
.domain([0, .15])
.range(d3.range(9).map((i) -> "q" + i + "-9" ))
You should probably just do:
quantize = d3.scale.quantize()
.domain([0, .15])
.range(d3.range(9).map((i) -> "q" + i + "-9" ))
so that quantize remains a function.
You should then remove the @ of the @quantize
, that translates in Javascript to this.quantize, as quantize seem to be a variable and not a property. Difference between properties and variables
Upvotes: 3