我是JavaScript的新手,并使用CoffeeScript学习。我想创建一个类,在初始化时使用Ajax与 Flickr Web API 进行通信。
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
)
我写了一个 Jasmine 测试来测试类的初始化。
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')
)
)
但photo.json
始终为空。
谢谢你的善意。
答案 0 :(得分:1)
$.ajax
在设置对象的上下文中调用其回调函数:
上下文对象
此对象将成为所有与Ajax相关的回调的上下文。默认情况下,上下文是一个对象,表示调用中使用的ajax设置(
$.ajaxSettings
与传递给$.ajax
的设置合并)。
所以@
不是你的回调中的Photo对象,它是一些对你没用的设置对象。但是,如果您通过使用fat-arrow (=>
):
_getJson
来将_getJson: (data) =>
@json = data.photos.photo
绑定到您的照片上
@
然后@json
将是您的照片,而{{1}}最终会成为您正在寻找的照片。
您可能遇到的下一个问题是,当Jasmine尝试查看它是否有效时,您的AJAX调用不一定会返回。我对Jasmine并不熟悉,但人们似乎喜欢this answer on testing AJAX with Jasmine;还有http://github.com/pivotal/jasmine-ajax用于存根AJAX部分以避免异步部分。