2017-03-08 49 views
0
class MyClass 
    defaultOptions: 
    url: '/photos.json' 

    constructor: (@element, @options) -> 
    @photos = [] 
    @init() 

    addPhotos: (photo) -> 
    @photos.push photo 

    request: -> 
    $.getJSON(this.defaultOptions.url).done((data) ->   
     @addPhotos data 
     return 
    ).fail (jqxhr, textStatus, error) -> 
     err = textStatus + ', ' + error 
     console.log 'Request Failed: ' + err 
     return 

    init: -> 
    @request() 

實例方法。當我從控制檯爲什麼不能調用裏面方法

var myClass = new MyClass("#myElement") 

我得到這個錯誤

TypeError: this.addPhotos is not a function. (In 'this.addPhotos(data)', 'this.addPhotos' is undefined) 

任何想法,爲什麼我不是能夠調用運行此命令請求方法內部的addPhotos方法,我怎麼稱呼它?

+1

看一看這裏箭頭怎麼發處理http://stackoverflow.com/questions/13184209/when-does-the-fat-arrow-bind-to-this-instance/13184211#13184211 – robkuz

回答

2

您需要使用fat arrow將外部上下文綁定到您的$.getJSON回調。

request: -> 
    $.getJSON(this.defaultOptions.url).done (data) => 
     @addPhotos data 
相關問題