angualr2封装组件(二)function怎么调用ts类的方法

    在使用echarts作自己图表的时候,遇到了function怎么调用组件的方法的问题。先说下自己的整个过程,答案在最下面。

需求是基于如何给图标的 图例添加click事件的,当时就纳闷了这个应该不简单,于是看了官方文档,不是很难,简单吗。于是乎就开始了。

图表绑定事件:由于是封装单击事件提供信息给外界的,所以用到了@Output。下面的代码会报错的,提示 this.chartEmit不是一个function。

export class DocChartComponent implements OnInit,OnChanges  {

@Output()  onLegendClick = new  EventEmitter<any>();
chart:any;
  ngOnInit() {
  

    this.chart=echarts.init(document.getElementById("main"));
    this.chart.setOption(this.options);
this.chart.onLegendClick = this.onLegendClick;
     
     this.chart.on('click',function(params){
        this.chartEmit(params);
  }
public  chartEmit(params:any){
  alert(params);
  this.onLegendClick.emit(params);
}
}

刚开始以为是function里不能调用ts组件的方法,于是乎就在function调用ts方法了,这么调用

export class DocChartComponent implements OnInit,OnChanges  {

@Output()  onLegendClick = new  EventEmitter<any>();
chart:any;
  
  ngOnInit() {
    this.chart=echarts.init(document.getElementById("main"));
    this.chart.setOption(this.options);
this.chart.onLegendClick = this.onLegendClick;
     
     this.chart.on('click',function(params){
        DocChartComponent com = new DocChertComponent()
            com.chartEmit(params) }

public  chartEmit(params:any){
  alert(params);
  this.onLegendClick.emit(params);
}
 
}

写完之后我觉得代码很奇怪,在自己的组件里实例化该组件。而且由于实例化了新的组件 @Output的方法根本不起作用,无法emit出信息。于是乎用了this关键字。

    
     this.chart.on('click',function(params,obj){
        let com = this;
        com.chartEmit(params);

       })  

发现依旧报错,chartEmit不是一个function。于是想到了this是不是不对,打印出了this关键字,发现 this是指向了 this.chart这个关键字,原来在function里的this指代的是上一级的对象,突然想到了匿名函数。我靠,原因在这里。找到原因了,解决办法也就好解决了。把组件中的方法赋值给this.chart这个元素。

 this.chart.chartEmit= this.chartEmit;
this.chart.onLegendClick = this.onLegendClick;
     
     this.chart.on('click',function(params,obj){
        this.chartEmit(params);

       })   


最后总结下:function里实例化类,然后调用这个类的方法,和面向对象是一样的,本组件的function调用本组件的method就可以采用上面给对象动态赋值匿名函数的办法了。




  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 24
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 24
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值