【问题标题】:class initialization always fails类初始化总是失败
【发布时间】:2012-10-29 10:48:29
【问题描述】:

我是 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 始终为空。

谢谢你的好意。

【问题讨论】:

    标签: javascript ajax coffeescript jasmine


    【解决方案1】:

    $.ajax 在设置对象的上下文中调用其回调函数:

    上下文对象

    这个对象将成为所有 Ajax 相关回调的上下文。默认情况下,上下文是一个表示调用中使用的 ajax 设置的对象($.ajaxSettings 与传递给 $.ajax 的设置合并)。

    所以@ 不是您回调中的 Photo 对象,它是一些对您几乎没有用处的设置对象。但是,如果您通过使用fat-arrow (=>) 定义您的照片将_getJson 绑定到您的照片:

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

    然后@ 将成为您的照片,@json 最终将成为您正在寻找的内容。

    您可能会遇到的下一个问题是,当 Jasmine 尝试查看它是否有效时,您的 AJAX 调用不一定会返回。我对 Jasmine 不太熟悉,但人们似乎喜欢 this answer on testing AJAX with Jasmine;还有 http://github.com/pivotal/jasmine-ajax 用于存根 AJAX 部分以避免异步部分。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-15
      • 1970-01-01
      • 1970-01-01
      • 2016-03-25
      • 2012-11-17
      • 2017-12-10
      • 2018-09-17
      • 1970-01-01
      相关资源
      最近更新 更多