微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 如何在ajax调用期间保持在此上下文中(jquery coffescript)

我做了一堂课:

class @GameMap
    options : {
        'width' : 100,'height' : 100,'tileWidth' : 45,'tileHeight' : 20,'scale' : 5,'movedistance' : 100,#distance to move with the map controlers
        'showErrorMessages' : true,'zindexDecorElementBase' : 99999,'zindexGroudElementBase' : 88888
    }

    lang : {
        'errContainerMissing' : "L'élement pour créer la carte n'existe pas"
    }

    constructor: (@element) ->
      this.run()

    run: ->
      this.loadDatas()

    loadDatas: (top,left) ->
      $.ajax(
          url: "/map/getnewcoord",data: {
             map_width : this.options.width,map_height : this.options.height,tile_height : this.options.tileHeight,tile_width : this.options.tileWidth,window_large : $('.map-windows').width(),window_height:  $('.map-windows').height(),top : top,left : left
          },success: (data) ->
            $.each(data,(index,item) ->
              this.createTile(item.posX,item.posY);
            )
      )

    createTile: (m,n) ->
       #We are in the tile reference
       yDelta = Math.round((options.width ) * options.tileHeight );
       console.log('pass')

  $->
    gamemap = new GameMap("#map .block-map")

但我得到了错误

this.createTile is not a function

这是因为“this”不是我班级的“this”,而是我的json调用返回的项目之一.

如何在ajax成功回调函数中保持我的班级“this”?

解决方法

这是CoffeeScript的方法

success: (data) =>
        $.each(data,item) =>
          this.createTile(item.posX,item.posY);
        )

这编译成与alex的答案非常相似的东西,但我认为,它更具可读性. =>运算符在使用定义函数时定义函数,而不是在调用它时.

虽然我们正在使用它,但您可能会发现使用@而不是使用它更具可读性:

@createTile(item.posX,item.posY);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐