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.
$.ajaxcalls its callback functions in the context of a settings object: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_getJsonto your Photo by defining it with a fat-arrow (=>):then
@will be your Photo and@jsonwill 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.