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

When I run this command from the console

var myClass = new MyClass("#myElement")

I get this error

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

Any idea why Im not being able to call addPhotos method inside the request method and how could I call it?

Martin
  • 11,216
  • 23
  • 83
  • 140
  • 1
    Have a look how fat arrow is handled here http://stackoverflow.com/questions/13184209/when-does-the-fat-arrow-bind-to-this-instance/13184211#13184211 – robkuz Mar 08 '17 at 17:18

1 Answers1

2

You need to use the fat arrow to bind the outer context to your $.getJSON callback.

request: ->
    $.getJSON(this.defaultOptions.url).done (data) => 
        @addPhotos data
pdoherty926
  • 9,895
  • 4
  • 37
  • 68