2013-02-19 84 views
1

我有一個CoffeeScript對象,在觸發操作後給我一個奇怪的錯誤。Coffeescript對象方法不是函數

的對象加載無事,但一旦動作完成後觸發回調我收到錯誤:

this.update不是一個函數 返回this.update(值);

有沒有人有一個想法,爲什麼發生這個錯誤?我最好的猜測是這個這個對象裏面的jQuery.rating調用實際上是指一個jQuery對象,而不是評級對象?

我CoffeeScript的代碼是:

jQuery -> 
    new Rating() 

class Rating 
    constructor: -> 
     $('.auto-submit-star').rating 
      callback: 
       (value, link) -> @update value 

    update: (value) => 
     $.ajax 
      type: 'post' 
      url: $('#new_rating').attr('action') 
      data: 'rating': value 
     .done (msg) -> 
      alert(msg) 

代碼編譯爲:

var Rating, 
    __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; 

Rating = (function() { 

    function Rating() { 
    this.update = __bind(this.update, this); 
    $('.auto-submit-star').rating({ 
     callback: function(value, link) { 
     return this.update(value); 
     } 
    }); 
    } 

    Rating.prototype.update = function(value) { 
    return $.ajax({ 
     type: 'post', 
     url: $('#new_rating').attr('action'), 
     data: { 
     'rating': value 
     } 
    }).done(function(msg) { 
     return alert(msg); 
    }); 
    }; 

    return Rating; 

})(); 

回答

3

rating插件可能調用callback作爲一個簡單的功能或DOM元素,以便@的情況下(AKA this)可能是window或您的.auto-submit-star元素。在任何情況下,@不是您的Rating對象,並且沒有update方法,因此您收到錯誤消息。

的標準方法是通過使用綁定功能fat-arrow (=>)

$('.auto-submit-star').rating 
    callback: 
     (value, link) => @update value 
+0

感謝您的信息,你是正確的脂肪箭頭解決了這個問題。欣賞信息。 – Asciant 2013-02-19 07:24:02

0

我遇到了一個類似的錯誤:與「fn.apply不是一個函數」,它原來是,我有一個與方法名稱相同的構造函數參數。

do-> 
 
    angular.module 'myservices' 
 
    .service 'averyspecialservice', ['$log', '$rootScope' 
 
    class AVerySpecialService 
 
     constructor: (@log, @rootScope)-> 
 

 
     log: (message)=> 
 
     //do some magic here 
 
     return 
 
    ] 
 
    return

所以「登錄」被定義爲兩個的方法和注射值和這樣一個模糊的錯誤信息找到錯誤的原因證明的樂趣... JavaScript不精彩。

相關問題