【问题标题】:How to stay in the this context during an ajax call (jquery + coffescript)如何在 ajax 调用期间保持在此上下文中(jquery + coffeescript)
【发布时间】:2012-01-23 01:09:45
【问题描述】:

我上课了:

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 不是函数

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

如何在 ajax 成功回调函数中保留我的类的“this”?

【问题讨论】:

    标签: javascript jquery ajax coffeescript


    【解决方案1】:

    这是 CoffeeScript 的做法:

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

    这编译为与亚历克斯的答案非常相似的东西,但我认为更具可读性。 => 运算符定义一个函数,同时使用定义时存在的 this,而不是调用它时。

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

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

    【讨论】:

    【解决方案2】:

    保留对this的引用。

    很多人使用var that = this(或self,如果它更适合您)这样的模式。

    然后,在您的内部函数中,将 this 的引用替换为 that,这将是父函数的 this

    或者,您可以使用 $.proxy()... 包装匿名函数定义...

    fn = $.proxy(fn, this);
    

    ...这将确保内部的this 始终是父级的this$.proxy() 是一种实现bind() 的跨浏览器方式(在旧版 IE 或 Safari 中未实现)。

    【讨论】:

    • 我建议使用 self. self = this,self.createTile。更直观
    【解决方案3】:

    您可以将context 作为参数传递给ajax() 方法:

    $.ajax({ /*...,*/ context: this/*, ...*/ });
    

    http://api.jquery.com/jQuery.ajax/

    【讨论】:

    • 谢谢,但问题来自每个函数,它没有保留 this 上下文。
    • 所以,您可以将我的答案与 alex 的答案混为一谈。或者改用他的解决方案。
    猜你喜欢
    • 2014-02-04
    • 2012-05-31
    • 2012-06-04
    • 1970-01-01
    • 2013-03-17
    • 2022-09-23
    • 2016-06-19
    • 2018-05-31
    • 2011-12-31
    相关资源
    最近更新 更多