ES6 class 使用绑定与调用在 class 中调用方法?

ES6 class calling a method within a class with bind vs call?

我有一个用 ES6 编写的 class,我有一个指令 "action",它需要访问一个名为 "selected" 的控制器值。此控制器值 "selected" 由另一个指令 "grid" 更新。 (2 种方式绑定)

我需要将 "selected" 值从已由指令 "grid" 更新的控制器传递到指令 "actions" on-select 。我试图通过执行 "bind" 但我得到一个类型错误 "cannot read actionHandler of undefined"

我不确定处理此问题的最佳方法是什么,这样当 "selected" 值已被 "grid" 指令更新时,actionEvent 会被更新后的值触发控制器。这些指令工作正常,我能够看到它在断点处中断。

这是我在 HTML

中的内容
<div class="col-xs-9">          
   <action options="ctrl.Actions" on-select="ctrl.actionEvent">
   </action>
</div>
<div class="col-xs-12">
  <grid config="ctrl.gridOptions" data="ctrl.data" selected="ctrl.selected"></grid>
 </div>

在控制器中,

 class CheckC {
   constructor($scope) {
    this.$scope = $scope;       
    this.selected = this.$scope.selected;
  }

actionEvent() {
    this.actionHandler.bind(this);
}

actionHandler(item, event) {
    let selection;
    let model = this.selected;
    if(model) {
        item.id = 1;
    }
 }
 }

首先,不要混淆.bind().call()

  • 首先 returns 一个新的函数实例,可以稍后调用,但会保留 this
  • 第二次调用立即生效,但修改 this 的上下文 用于此调用。

阅读this answer了解更多信息

您正在传递对 actionEvent 方法的引用。在调用的那一刻,对原始控制器对象的引用已经丢失。

要保留引用,您需要先在构造函数中保存它

class CheckC {
  constructor($scope) {
    this.$scope = $scope;       
    this.selected = this.$scope.selected;
    //bind method here
    this.actionEvent = this.actionEvent.bind(this);
  }

  actionEvent(item, event) {
    // this here will be always contain a referene to class instance
    this.actionHandler(item, event);
  }

  actionHandler(item, event) {
    let selection;
    let model = this.selected;
    if(model) {
      item.id = 1;
    }
  }
}

同样在您的代码中 actionEvent 方法似乎是多余的。考虑重构代码并直接传递 actionHandler。 (不要忘记更新 .bind() 调用,它应该在 actionHandler 之后绑定)。