在农业电网事件中引用“ this” [英] referencing 'this' in ag-grid events

查看:99
本文介绍了在农业电网事件中引用“ this”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在农业电网事件中,例如onRowSelected(),此是指网格对象。但是,我需要引用组件变量并且不知道该怎么做。我所做的就是这个,但这是一个hack:

In ag-grid events, e.g. onRowSelected(), 'this' refers to the grid object. However, I need to reference component variables and don't know how to. What I did was this, but it is a hack:

initializeGridOptions() {
    this.gridOptions = {
      columnDefs: [
        { headerName: "Core #", field: "coreNumber", width: 100, sort: 'asc' },
      onRowSelected: this.onRowSelected,
    }
    this.gridOptions['_this'] = this;  // HACK
  }

  onRowSelected(event: any) {
    if (event.node.selected) {
      (this as any)._this.selectedNode = event.node.data;
    }
  }

是否有更好的方法?

推荐答案

枚举可以解决 this 问题的各种方法-

1.使用箭头功能:

Enumerating the various ways you could solve this problem -
1. Use of arrow function:

   onRowSelected : (event: any) => { ... }

2。 bind()的使用:

onRowSelected:this.onRowSelected.bind(this)

如果您的 onRowSelected
组件紧密耦合,并且只能与该网格一起使用,则此方法很有用。

onRowSelected: this.onRowSelected.bind(this)
This approach is useful if your onRowSelected is tightly coupled to your component and it is meant to be used only with that grid.

3。使用ag-grid context gridOption:

3.Use of ag-grid context gridOption:

但是,如果您希望在多个网格之间共享一个功能,并且可以说在网格实用程序服务中具有此功能。

然后,您可以使用以下方法。在gridOptions中,使用上下文选项

However if you would want to share a single function across many grids and lets say have this function in a grid utility service.
Then you can use the below approach. In gridOptions, use the context option

gridOptions = {context:{parentComponent:this} ...} < br>
onRowSelected:this.gridUtilityService.onRowSelected

onRowSelected之内您可以使用以下内容访问上下文:

const ctx = params.context.parentComponent 引用组件变量

Within onRowSelected you can access context using :
const ctx = params.context.parentComponent to reference component varibles

这篇关于在农业电网事件中引用“ this”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆