Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 801
Daniel Fischer Avatar asked Sep 15 '11 12:09

Daniel Fischer


People also ask

How do you write a function in CoffeeScript?

To define a function here, we have to use a thin arrow (->). Behind the scenes, the CoffeeScript compiler converts the arrow in to the function definition in JavaScript as shown below. (function() {}); It is not mandatory to use the return keyword in CoffeeScript.

What is CoffeeScript written in?

CoffeeScript is a programming language that compiles to JavaScript. It adds syntactic sugar inspired by Ruby, Python, and Haskell in an effort to enhance JavaScript's brevity and readability. Specific additional features include list comprehension and destructuring assignment.

Is CoffeeScript same as JavaScript?

CoffeeScript is a lightweight language that compiles into JavaScript. It provides simple and easy-to-learn syntax avoiding the complex syntax of JavaScript. CoffeeScript is influenced by JavaScript, Ruby, YAML, Haskell, Perl, Python and has influenced MoonScript, LiveScript, and JavaScript.


2 Answers

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
like image 168
Ricardo Tomasi Avatar answered Oct 06 '22 00:10

Ricardo Tomasi


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 ;)

like image 31
Arnaud Le Blanc Avatar answered Oct 05 '22 23:10

Arnaud Le Blanc