Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stay in the this context during an ajax call (jquery + coffescript)

I made a class :

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")

But i got the error

this.createTile is not a function

It's because the "this" is not the "this" of my class but one of item return by my json call.

How can i do to keep the "this" of my class in the ajax success callback function?

like image 974
Sebastien Avatar asked Dec 01 '25 10:12

Sebastien


1 Answers

Here's the CoffeeScript way to do it:

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

This compiles to something very similar to alex's answer, but is, I think, much more readable. The => operator defines a function while using the this that was present when it was defined, rather than when it was called.

While we're at it, you may find it more readable to use @ instead of this:

          @createTile(item.posX,item.posY);
like image 171
Aaron Dufour Avatar answered Dec 03 '25 00:12

Aaron Dufour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!