繁体   English   中英

如何从角度2的回调函数中调用父函数?

[英]How to call parent function from callback function in angular 2?

这是一堂课

export class ChatDetailPage {

constructor(){

}

funcA(){
     var options = {
        onSubmit: function (text) {
        //i want to be able to access funcB from here 
        this.funcB(text)
          },
this.nativeKeyboard.showMessenger(options)
}

funcB(text){
  alert (text);
}

}

在这种情况下,如何在Anular 2或Ionic 3中的onsubmit回调函数中调用funcB。

提前致谢。

使用箭头函数,它捕获了this的值:

export class ChatDetailPage {

    constructor(){

    }

    funcA(){
       var options = {
           onSubmit: text => {
              //i want to be able to access funcB from here 
              this.funcB(text)
           },
       };
       this.nativeKeyboard.showMessenger(options)
   }

   funcB(text){
      alert (text);
   }
}

有时,当它是内置函数或库函数时,您将无法使用箭头函数。 在这种情况下,可以使用的解决方案是将this变量绑定到名为self或任何您想要的变量。

funcA(){
     // bind the this variable to 'self' outside of the function scope
     var self = this;
     var options = {
        onSubmit: function (text) {
            // and use self instead of this 
            self.funcB(text)
        },
     this.nativeKeyboard.showMessenger(options)
}

funcB(text){
  alert (text);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM