首页 > 解决方案 > Ember.js 中 `this` 的基本使用

问题描述

我相当擅长 Javascript,但我很难理解 Emberthis在某些情况下是如何处理上下文的。

我有一个组件控制器:

import Component from '@ember/component';

export default Component.extend({
  keyPress(e) {
    // here I want to call a method in the `actions` hash
    this.get('onAccept')
  },

  actions: {
    onAccept() {
      console.log('action accepted!')
    }
  }
}

每次我运行它时,我都会收到以下错误:

Uncaught TypeError: this.get(...) is not a function

actions当我在散列之外有一个方法需要访问散列内部的函数时,这似乎总是发生actions或者相反。

这种行为似乎是必要的,因为组件事件属于操作 hash 之外

那么我应该如何在actions散列之外拥有事件方法,但仍然能够调用属于actions散列内部的方法呢?

这似乎是 Ember 控制器中记录不充分的部分。也许我只是在这里遗漏了一些东西。任何帮助是极大的赞赏。

标签: javascriptember.js

解决方案


要从actions哈希外部调用操作,请使用this.send

this.send('onAccept');

更多信息可以在这里找到:sendhttps ://medium.com/ember-titbits/ember-send-and-sendaction-5e6ac9c80841sendAction


推荐阅读