Javascript 如何在ajax调用(jquery+;coffescript)期间保持这种上下文
我上了一节课:Javascript 如何在ajax调用(jquery+;coffescript)期间保持这种上下文,javascript,jquery,ajax,coffeescript,Javascript,Jquery,Ajax,Coffeescript,我上了一节课: class @GameMap options : { 'width' : 100, 'height' : 100, 'tileWidth' : 45, 'tileHeight' : 20, 'scale' : 5, 'moveDistance' : 100, #Distance to move with the map controlers 'showError
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调用返回的项之一
如何将类的“this”保留在ajax成功回调函数中?保留对
this
的引用
很多人使用一种模式,比如var=this
(或者self
,如果它对你更合适的话)
然后,在内部函数中,将对this
的引用替换为that
,这将是父函数的this
或者,您可以将匿名函数定义包装为
…这将确保内部的
this
始终是父级的this
$.proxy()
是一种跨浏览器的方式,用于实现bind()
(在旧版IEs或Safari中未实现)。您可以将上下文作为参数传递给ajax()
方法:
$.ajax({ /*...,*/ context: this/*, ...*/ });
以下是咖啡脚本的方法:
success: (data) =>
$.each(data,(index,item) =>
this.createTile(item.posX,item.posY);
)
这与alex的答案非常相似,但我认为更具可读性。=>
运算符在使用定义时而不是调用时出现的此
时定义函数
当我们进行此操作时,您可能会发现使用@
而不是此
更具可读性:
@createTile(item.posX,item.posY);
谢谢,但是问题来自于没有保留上下文的each函数。所以,你可以把我的答案和alex的答案混合起来。或者使用他的解决方案。我建议使用self。self=this,self.createTile。CoffeScript文档中的“胖箭”解释更直观:
@createTile(item.posX,item.posY);