Reputation: 7088
I'm new at CoffeeScript and I'm having trouble understanding some syntax of it.
For example, in this function call:
e('')
.color('rgb(255,0,0)')
.attr( x: 20,
y: 100,
w: 10,
h: 100 )
I'm expecting this to compile JS code that passes an object with keys x, y, w, h to attr
method. But this code actually compiles to this:
e('').color('rgb(255,0,0)').attr({
x: 20
}, {
y: 100,
w: 10,
h: 100
});
It's passing two objects to attr
, first with key x
, and second with keys y
, w
, and h
. I'm having trouble understanding why is x separated from other keys, but other keys are not separated from each other?
Since I want to pass attr
method one object, I tried this:
e('')
.color('rgb(255,0,0)')
.attr({x: 20,
y: 100,
w: 10,
h: 100})
But this gives me that compile error in the line that y: 100
gets place: Error: Parse error on line 4: Unexpected '{'
. The strange thing is, there is no {
in line 4. I also tried removing parens in attr
but still got the same error.
I can solved it with this:
e('')
.color('rgb(255,0,0)')
.attr(
x: 20,
y: 100,
w: 10,
h: 100)
If I remove the newline after .attr(
, then I'm getting the same code in my first example, which is not what I want.
Now I'm wondering if I'm misunderstanding some points in CoffeeScript syntax or there are really strange stuff in it. Or did I catch a bug in CoffeeScript? Any ideas?
I'm using CoffeeScript 1.3.1
Upvotes: 0
Views: 535
Reputation: 35706
This is what you're looking for:
e('')
.color('rgb(255,0,0)')
.attr
x:20
y:100
w:10
h:100
which compiles to:
e('').color('rgb(255,0,0)').attr({
x: 20,
y: 100,
w: 10,
h: 100
});
remember, CoffeeScript is all about simplicity and avoiding curly braces and commas...
Upvotes: 1
Reputation: 18288
In coffeescript whitespace is significant. You can't just line things up whereever you think they should go. Try something like this:
e('')
.color('rgb(255,0,0)')
.attr(
x: 20
y: 100
w: 10
h: 100
)
Edit: If you want to have x on the same line as the method call you just need to indent properly:
e('')
.color('rgb(255,0,0)')
.attr(x: 20,
y: 100,
w: 10,
h: 100)
Upvotes: 3
Reputation: 12275
The obvious solution would be to put your object on one line, as in .attr({x: 20, y: 100, w: 10, h: 100})
. (Haven't tested it though, but I don't see why it would not work).
While you can sometimes not use the brackets, I prefer to use them in functions calls as I find it more readable.
Upvotes: 0