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方法,我怎么能调用它?
答案 0 :(得分:2)
您需要使用fat arrow将外部上下文绑定到$.getJSON
回调。
request: ->
$.getJSON(this.defaultOptions.url).done (data) =>
@addPhotos data