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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With