2

我在打字稿中使用 alertify 插件,它无法识别该getData功能。请看下面的代码

copyTemplate(id:any, pluginId:any, name:any ) {
     alertify.confirm(`Are you sure you want to copy ${name} to a new project template?`, function () {
        this.getData();
     }, function() {
          (<HTMLInputElement>document.getElementById('prefGroup')).value = '0';
     });
}

它出什么问题了?浏览器错误:

ts:135Subscriber.next@Subscriber.ts:95Subject.next@Subject.ts:61EventEmitter.emit@core.umd.js:3675NgZone.triggerError@core.umd.js:4038onHandleError@core.umd.js:3999ZoneDelegate.handleError@ zone.js?1489977130473:207Zone.runTask @ zone.js?1489977130473:139ZoneTask.invoke @ zone.js?1489977130473:304 core.umd.js:3070 TypeError: this.getData is not a function at Object.eval [as onOkay ] (project-templates.component.ts:126) 在 HTMLButtonElement。(alertify.js?1489977130519:280) 在 ZoneDelegate.invokeTask (zone.js?1489977130473:236) 在 Object.onInvokeTask (core.umd.js:3969) 在 ZoneDelegate.invokeTask (zone.js?1489977130473:235) 在 Zone .runTask (zone.js?1489977130473:136) 在 HTMLButtonElement.ZoneTask.invoke (zone.js?1489977130473:304)ErrorHandler.handleError @ core.umd.js:3070next @ core.

4

1 回答 1

3

使用箭头函数。“this”的范围在回调内部是不同的

copyTemplate(id:any, pluginId:any, name:any ) {
 alertify.confirm('Are you sure you want to copy ${name} to a new project template?',  () => {
    this.getData();
 }, () => {
      (<HTMLInputElement>document.getElementById('prefGroup')).value = '0';
 });

}

或将 this 的值存储在函数之外并使用它

copyTemplate(id:any, pluginId:any, name:any ) {
 let self = this;
 alertify.confirm('Are you sure you want to copy ${name} to a new project template?',  function() {
    self.getData();
 }, function() {
      (<HTMLInputElement>document.getElementById('prefGroup')).value = '0';
 });

}

于 2017-03-20T02:38:54.233 回答