2014-09-04 19 views
0

有下面的代碼:JS消息 '不是一個函數' 中的CoffeeScript

class OrdersBySalonUpdater 

    sendRequestToUpdateOrders: -> 
     console.log('123') 
     startDate = transformDate($("#from_datepicker")) 
     endDate  = transformDate($("#to_datepicker")) 
     businessId = $(".maininfo__datepickerwrap").attr("data-business-id") 

     url = "some url" 

     $.get url, (data) -> 
      @updateOrders(data.orders) 

    updateOrders: (orders) -> 
     $("#salon_stat_table tr").slice(1).remove() 
     $.each orders, (index) -> 
      console.log(orders[index]) 

但是,當我執行以下命令:

x = new OrdersBySalonUpdater() 
    x.sendRequestToUpdateOrders() 

我得到的消息「類型錯誤:this.updateOrders不是一個功能「。我該如何解決它?有什麼問題?謝謝。

回答

1

在JavaScript中,this是一個上下文對象。它可以改變,往往當我們不希望它。

當您編寫@updateOrders(data.orders)時,CoffeeScript將其轉換爲JavaScript this.updateOrders(data.orders)。但是,您在從jQuery的$.get回調中調用updateOrders。當您的代碼執行後,this不再指您的OrdersBySalonUpdater類 - 它是the context passed in the Ajax settings, or the settings themselves


有三種方法可以解決這個問題。最後是最好的 - 它是最短的,也是最習慣的CoffeeScript。

  1. 商店this的電流值,你的回調中使用它。 this可以更改,但如果我們將其當前值存儲在變量中,那麼稍後可以使用它。這是一個常見的約定來調用這些變量that

    sendRequestToUpdateOrders: -> 
        that = this 
        url = "some url" 
    
        $.get url, (data) -> 
        that.updateOrders(data.orders) 
    
  2. this到回調的背景下。 jQuery讓我們將context選項傳遞給我們的Ajax方法。無論我們通過將在回調中可作爲this

    sendRequestToUpdateOrders: -> 
        url = "some url" 
    
        $.get url, 
        success: (data) -> 
         @updateOrders(data.orders) 
        context: this 
    
  3. 使用CoffeeScript的脂肪箭頭寫回調。脂肪箭頭defines a function and binds this for you

    sendRequestToUpdateOrders: -> 
        url = "some url" 
    
        $.get url, (data) => 
        @updateOrders(data.orders)