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.
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.
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.
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.
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
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 ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With