2016-07-22 85 views
9

我正在關注此railscast https://www.youtube.com/watch?v=ltoPZEzmtJA,但我不使用coffeescript。我試圖將咖啡轉換爲JavaScript,但我遇到了問題。將coffeescript函數轉換爲javascript

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文件

$(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) 

}); 

我不明白爲什麼他決定做一個類,並認爲這將是更爲複雜的整體轉換事情。我遇到的麻煩是更新功能。我只是把咖啡腳本的更新功能插入轉換器並使用輸出。這是導致錯誤說沒有定義更新。我哪裏錯了?

還有一個問題:他在這裏上課的意義何在?

謝謝!

+1

您可以使用此轉換http://js2.coffee/ –

+0

「爲什麼要使用類,你可以用C寫!「 – metalim

+0

我一直在閱讀Javascript的好的部分和「構建一個類的方法」在那裏與隱私的優勢,即暴露一個對象的更少的屬性 – engineerDave

回答

7

您的語法看起來不對...... :用於聲明帶標記的語句。

這是一個正確的方法。聲明一個懸掛的變量並分配一個函數ref。到它。 函數名稱也可以出現在表達式函數中,所以它可以使用它的名字來引用它本身。

使用var函數變量應該提升,除了賦值。

/* there are various ways to declare a function */ 

function update(coords) { 
    var $users = $('.user'); 
    $users.val(coords.x); 
    $users.val(coords.y); 
    $users.val(coords.w); 
    return $users.val(coords.h); 
} 
+0

對不起,我的代碼錯了,coords應該是x, y,w,h我會改變它..抄寫錯誤 – user4584963

+0

@ user4584963完成... – Hydro

+0

另外,在railscast中,他提出了一個觀點,他說他正在使用胖箭頭......關於上下文的一些問題,我不確定是什麼意即。你的回答是否解釋了這個問題? – user4584963

2

一類的觀點:

  • 使其更容易與碰撞更少的空間上不同的元素相同的任務多次運行。當
  • 幫助智障組織代碼

要轉換,使用這樣的網站http://js2.coffee/

var AvatarCropper, 
    bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; 

jQuery(function() { 
    return new AvatarCropper(); 
}); 

AvatarCropper = (function() { 
    function AvatarCropper() { 
    this.update = bind(this.update, this); 
    $('#cropbox').Jcrop({ 
     aspectRatio: 1, 
     setSelect: [0, 0, 600, 600], 
     onSelect: this.update, 
     onChange: this.update 
    }); 
    } 

    AvatarCropper.prototype.update = function(coords) { 
    $("#crop_x").val(coords.x); 
    $("#crop_y").val(coords.y); 
    $("#crop_w").val(coords.w); 
    return $("#crop_h").val(coords.h); 
    }; 

    return AvatarCropper; 

})(); 

// --- 
// generated by coffee-script 1.9.2