我正在将一些 javascript 代码移植到打字稿上,但遇到了一个问题。
我有一个 ajax 调用,它将一个对象作为上下文传递,该对象包含一些回调和一些其他信息,这些信息由成功或错误回调读出,这些信息指示成功调用应重定向到的位置:
function SomeAjaxService
{
var self = this;
self.CheckErrorType = function(...) {
// Do something
};
var SuccessProxyCallback = function(results) {
// Do some stuff with results, like send off some events
this.successCallback(results);
};
var FailureProxyCallback = function(...) {
// Do some stuff with errors, and fire some events
var someErrorType = self.CheckErrorType(...);
this.failureCallback(someErrorType);
};
self.SendRequest = function(requestArgs) {
var ajaxSettings = {
context: requestArgs,
// Assign a load of stuff
};
$.ajax(ajaxSettings);
};
}
现在您可以看到失败代理调用本地方法以及使用“this”上下文对象。那么如何使用 typescript 处理这种情况呢?
您可以self = this
在构造函数中设置并像以前一样继续吗?
== 编辑 ==
正如这里所要求的那样,上面的类表示显示了由于缺少 self 变量而需要两件事的问题。
class SomeAjaxService
{
public CheckErrorType(someArg1: any, someArg2: any) {
// Do some stuff with data
};
private SuccessProxyCallback(results: any) {
// Do some stuff with results, like send off some events
this.successCallback(results);
// Does the above *THIS* usage point to the context of the
// Ajax call or the actual instantiated class
};
private FailureProxyCallback(...) {
// Do some stuff with errors, and fire some events
var someErrorType = this.CheckErrorType(...);
// The above *THIS* call cannot be correct if the context has overwritten
// the scope of this, however I dont know if this is true, do I even need
// this.CheckErrorType to invoke a local method?
this.failureCallback(someErrorType);
// As mentioned above same issue here but the *THIS* should hopefully
// point to the context object on the ajax object not the local instance.
};
public SendRequest(requestArgs: any) {
var ajaxSettings : JqueryAjaxSettings = {
context: requestArgs,
// Assign a load of stuff
};
$.ajax(ajaxSettings);
};
}
就像我在上面所说的那样,主要问题是在一个方法中我需要调用其中一个实例方法以及从 ajax 调用调用上下文对象上的方法。使用原始 javascript,我将拥有self = this
然后我可以绕过this
被覆盖,这是将 ajax 异步状态对象保持在范围内所必需的。