0

I am newbie of JavaScript and studying with CoffeeScript. I want to make a class which communicate to Flickr Web API with Ajax when initialized.

class Photo

  json: null

  constructor: ->
    @getJson()

  _getJson: (data) ->
    @json = data.photos.photo

  getJson: ->
    $.ajax(
      url : 'http://www.flickr.com/services/rest/'
      type : 'GET'
      data :
        format : 'json'
        method : 'flickr.photos.search'
        api_key : 'api_key'
        user_id : '29242822@N00'
        per_page : '100'
      dataType : 'jsonp'
      jsonp : 'jsoncallback'
      success : @_getJson
    )

I wrote a Jasmine test which test the initialization of the class.

describe("Photo", ->
  photo = new Photo
  console.log(photo.json)
  it("should get json when constructed", ->
    expect(photo.json).toBeDefined()
  )
  it("should have json which begins", ->
    expect(photo.json[0].title).beBe('Ridges of Shirouma')
  )
)

But photo.json is always null.

Thank you for your kindness.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
Feel Physics
  • 2,783
  • 4
  • 25
  • 38

1 Answers1

1

$.ajax calls its callback functions in the context of a settings object:

context Object

This object will be made the context of all Ajax-related callbacks. By default, the context is an object that represents the ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax).

So @ isn't your Photo object in your callback, it is some settings object that is of little use to you. But, if you bind your _getJson to your Photo by defining it with a fat-arrow (=>):

_getJson: (data) =>
  @json = data.photos.photo

then @ will be your Photo and @json will end up being what you're looking for.

The next problem you'll probably have is that your AJAX call won't necessarily have returned when Jasmine tries to see if it worked. I'm not that familiar with Jasmine but there is this answer on testing AJAX with Jasmine that people seem to like; there's also http://github.com/pivotal/jasmine-ajax for stubbing the AJAX part to avoid the asynchronous part.

Community
  • 1
  • 1
mu is too short
  • 426,620
  • 70
  • 833
  • 800