Reputation: 2272
I'm trying to make a very basic thing in CoffeeScript:
...
nextId = $('.optionsTemplate').prev().children().length + 1
# 'alert nextId' gives 4, which is correct
...
newOption = /*selector of new option*/
newOption.attr 'id', 'item_options_' + nextId
newOption.attr 'name', 'item[options]['+ nextId +']'
So when I call "nextId" (when setting id and name) - JS console says "nextId is not a function"
I tried a couple of things:
# get text instead of integer
nextId.text()
# make a function
getNextId = () ->
$('.optionsTemplate').prev().children().length + 1
Getting same error.
Here's compiled output:
$('.addOption').on('click', function() {
var contents, newOption, nextId;
nextId = $('.optionsTemplate').prev().children().length + 1;
contents = "<div class='row'>" + $('.optionsTemplate').html() + '</div>';
$(this).before(contents);
newOption = $('.optionsTemplate').prev().children().eq(-1).find('.text_field');
newOption.attr('id', 'item_options_' + nextId);
return newOption.attr('name', 'item[options][' + nextId(+']'));
});
Seems Ok to me.
Upvotes: 1
Views: 149
Reputation: 589
As has been mentioned, the problem exists in the final line:
newOption.attr 'name', 'item[options]['+ nextId +']'
The problem is that CoffeeScript is treating nextId as a function. The reason for this is that there is no space between the + symbol and the ']' string.
Adding the space as follows:
newOption.attr 'name', 'item[options]['+ nextId + ']'
makes everything work as expected. Just one of those things to be wary of with CoffeeScript - things don't always work as you expect first time due to significant whitespace.
Upvotes: 0
Reputation: 27382
return newOption.attr('name', 'item[options][' + nextId(+']'));
Change above to
return newOption.attr('name', 'item[options][' + nextId +']');
Upvotes: 2