user4584963 user4584963 - 4 months ago 18
CoffeeScript Question

Convert coffeescript function to javscript

I am following this railscast https://www.youtube.com/watch?v=ltoPZEzmtJA but I don't use coffeescript. I am trying to convert the coffeescript to javascript but I'm running into a problem.

coffeescript

jQuery ->
new AvatarCropper()

class AvatarCropper
constructor: ->
$('#cropbox').Jcrop
aspectRatio: 1
setSelect: [0, 0, 600, 600]
onSelect: @update
onChange: @update

update: (coords) =>
$("#crop_x").val coords.x
$("#crop_y").val coords.y
$("#crop_w").val coords.w
$("#crop_h").val coords.h


js.erb file

$(document).ready(function() {

$('.crop-image').on('click', function () {
$('#cropbox').Jcrop({
aspectRatio: 1,
setSelect: [0, 0, 100, 100],
onSelect: update,
onChange: update
})
});

update: (function(_this) {
return function(coords) {
$('.user').val(coords.x);
$('.user').val(coords.y);
$('.user').val(coords.w);
return $('.user').val(coords.h);
};
})(this)

});


I didn't understand why he decided to make a class and thought it would be more complicated to convert the whole thing. The trouble I'm having is the update function. I just plugged his coffee script for the update function into a converter and used the output. This is causing an error saying update is not defined. Where am I going wrong?

Also bonus question: what's the point of him making a class here?

Thanks!

Answer

Your syntax looks wrong... : is used when declaring properties in a object constructor.

Correct is:

function update(coords) {
    $('.user').val(coords.x);
    $('.user').val(coords.y);
    $('.user').val(coords.w);
    return $('.user').val(coords.h);
}

You can declare update with the var statement, also. The difference is cause function declaration with name goes to the top of the block.