我正在将一些 javascript 代码移植到 typescript,但遇到了一个问题。
我有一个将对象作为上下文传递的 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 变量而需要 2 件事的问题。
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 异步状态对象保持在范围内所必需的。
最佳答案
Can you just set self = this in the constructor and continue as you were before?
抽象地说,在构造函数中执行此操作通常不会解决任何问题(除非您稍后在该方法中捕获它——见下文)。 TypeScript 类将类实例数据存储在对象本身上,而不是捕获局部变量。因为 self
将存储在 this
对象中,所以您最终不会拥有以前没有的任何东西。
这是一种方法:
class SomeAjaxService
{
private FailureProxyCallback(context, arg) {
// now 'this' is the class instance and 'context' is requestArgs
}
public SendRequest(requestArgs) {
var self = this; // Note: captured local used in closure below
var ajaxSettings = {
context: requestArgs,
// Do not use an arrow function here, even though it's tempting!
error: function(arg) { self.FailureProxyCallback(this, arg) }
};
$.ajax(ajaxSettings);
};
}
关于javascript - Typescript + Jquery Ajax + 这个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15662038/