Javascript 类型脚本绑定问题
我正在尝试将此函数从prototype移植到typescript中的jquery:Javascript 类型脚本绑定问题,javascript,jquery,prototype,typescript,Javascript,Jquery,Prototype,Typescript,我正在尝试将此函数从prototype移植到typescript中的jquery: onFailure: function(xhr) { // Get options var opts = this; // Show result var msgBox = opts.msgBox ? opts.msgBox : opts.client.options.msgBox; if (msgBox && !opts.onFailure)
onFailure: function(xhr) {
// Get options
var opts = this;
// Show result
var msgBox = opts.msgBox ? opts.msgBox : opts.client.options.msgBox;
if (msgBox && !opts.onFailure) {
msgBox.showError('Communicatie fout.');
}
// Handle onFailure callback
if (opts.onFailure) {
opts.onFailure.bind(opts.client)(xhr);
}
else if (opts.options && opts.options.onFailure) {
opts.options.onFailure.bind(opts.client)(xhr);
}
// Fire event
opts.client.failureCb.fire('failure');
},
这是移植的代码:
onFailure(xhr){
// Get options
var opts = this;
// Show result
var msgBox = opts.msgBox ? opts.msgBox : opts.client.options.msgBox;
if (msgBox && !opts.onFailure) {
msgBox.showError('Communicatie fout.');
}
// Handle onFailure callback
if (opts.onFailure) {
opts.onFailure(opts.client)(xhr);
}
else if (opts.options && opts.options.onFailure) {
opts.options.onFailure.bind(opts.client)(xhr);
}
// Fire event
opts.client.failureCb.fire('failure');
}
正如你所看到的,没什么不同。但是,问题来自typescript编译器:
错误TS2094:类型为“null”的值上不存在属性“bind”
如何将其正确移植到jquery
谢谢。发生这种情况的唯一原因是typescript根据您编写的内容推断了类型:
var opts = {
options:{
onFailure: null
}
}
// The property 'bind' does not exist on value of type 'null'
opts.options.onFailure.bind();
通过将变量显式键入为any
,可以覆盖此行为:
var opts:any = {
options:{
onFailure: null
}
}
// no more error
opts.options.onFailure.bind();
这将删除编译错误,但我怀疑此编译错误可能指向代码中的有效逻辑错误。能否提供完整示例?我无法将此示例放入上下文中—如果我使用jQuery AJAX,我希望使用
.error(jqXHR jqXHR,String textStatus,String errorshown)
来处理AJAX故障。