Daniel Fischer
Daniel Fischer

Reputation: 3062

How would I write this jQuery in coffeescript?

Just trying to learn and confused on how to do the following. Thanks!

$.each($(".nested-fields"), function(intIndex) {$(this).find(".set").html(intIndex+1);;} );

Thank you again.

Upvotes: 9

Views: 7379

Answers (3)

gdoumenc
gdoumenc

Reputation: 599

Personally I like the for .. in .. of coffeescrip but I was boring using the following structure to have the iterator as JQuery object :

for td in $('td.my_class')
    $td = $(td)
    ..

So I defined a items function available to each JQuery object:

$.fn.items = -> $.map(this, $)

Now the navigation with coffeescript is simpler :

for $td in $('td.my_class').items()
    $td <-- is a JQuery object

Upvotes: 0

Ricardo Tomasi
Ricardo Tomasi

Reputation: 35253

The original javascript could (or should) be written like this:

$('.nested-fields').each(function(i){
  $(this).find('.set').html(i+1)
})

so

$('.nested-fields').each (i) ->
  $(this).find('.set').html i+1

a more readable version could look like this:

fields = $('.nested-fields')

for field, i in fields
  set = $(field).find('.set')
  set.html i+1

or

$(field).find('.set').html i+1 for field in fields

Upvotes: 20

Arnaud Le Blanc
Arnaud Le Blanc

Reputation: 99909

for field, i in $(".nested-fields")
    $(field).find('.set').html(i+1)

(This iterates over the array with a for (;;) loop.)

Or if you want to use $.each:

$.each $(".nested-fields"), (i) ->
    $(this).find('.set').html(i+1)

BTW the title is a little incorrect; should be how to write this Javascript in Coffeescript ;)

Upvotes: 3

Related Questions