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

来源:互联网 发布:linux ping指定接口 编辑:程序博客网 时间:2024/06/03 13:44

    在使用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就可以采用上面给对象动态赋值匿名函数的办法了。




原创粉丝点击