2016-12-25 84 views
0

我无法在回调函数中访问this,但我最终使用指向AJAX对象的this而不是this对象调用了onClickEmail函数。我试图在that变量中获得参考,但这也没有多大帮助。如何在AJAX调用的回调中访问正确的`this`?

什么我做错了这里:

onClickEmail() { 
    var that = this; 
    var hey = "xyz" 
    $.ajax({ 
    url: 'http://rest.learncode.academy/api/test123/tweets' 
    }).then(function(response) { 
    console.log(hey); 
    console.log(that); 
    }); 
} 

更比解决这个问题,我想知道那为什么我能读懂的hey变量,但that值是不确定的

+0

如果我能理解你想用“这”的,我可以有更多的帮助是什么。 – sheriffderek

+0

我正在使用emberjs创建一个web应用程序。这个方法'onClickEmail'在点击一个DOM元素时被调用。拥有这个'onClickEmail'方法的类有一些属性,只要我得到一个AJAX响应,我就需要访问这些属性。 –

回答

0

这一点 - 该变量指的是拥有该功能的对象。 使用绑定或尝试

var that = this; 
onClickEmail(){ 
    $.ajax({ 
      url: 'http://rest.learncode.academy/api/test123/tweets' 
     }).then(function(response) { 
      hey = that; 
     }); 
} 
+0

当我尝试访问“that”时,出现“Uncaught ReferenceError:未定义”错误。 –

+1

很难说没有完整的代码。你想在“那个”中加入什么? – DrobyshevAlex

+0

以下是完整的代码:https://github.com/cravi24/clientAppEmber/blob/master/app/controllers/home.js –

相关问题