我有一个用于 dojo 的 amd 的自定义模块,如下所示:
define(
"my/moduleName",
[//dependencies],
function(xhr) {
return {
method1: function() {
xhr.get({
url: "myurl",
load: function(data) {
//handle data
this.method2(data) //< THIS CAUSES ERROR: 'this.method2 is not a function'
}
});
},
method2: function(data) {
//process data
}
}
}
我怀疑我的问题是 xhr.get
创建了一个延迟对象,而 method2
没有在该对象中定义,而是在“my/module”对象上定义。
如何在 xhr
完成后调用 method1
?
最佳答案
您需要存储当前的 this
上下文,因为一旦您进入 load
函数上下文,this
就是 xhr 对象。
常见的约定是 var that = this;
,然后根据需要在任何其他闭包中使用 that
。
在类似于此的调用之前存储this
:
define(
"my/moduleName", [ //dependencies],
function (xhr) {
return {
method1: function () {
var that = this; //<-- store this context
xhr.get({
url: "myurl",
load: function (data) {
//handle data
that.method2(data); //<-- use that , the stored context
}
});
},
method2: function (data) {
//process data
}
}
}
<小时/>
DEMO - 存储this
以供以后在另一个闭包中使用
关于javascript - 在自定义 dojo amd 模块中的 xhr 请求后调用同级方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15228875/