我相当精通Javascript,但我很难理解Ember在某些情况下如何处理this
上下文。
我有一个组件控制器:
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
哈希中的函数时,或者相反,这似乎总是会发生。
这种行为似乎是必要的,因为组件事件属于操作哈希之外。
那么我应该如何在actions
哈希之外拥有事件方法,但仍然能够调用属于actions
哈希内部的方法呢?
这似乎是 Ember 中控制器的一个记录不佳的部分。也许我只是在这里错过了一些东西。任何帮助将不胜感激。
若要从actions
哈希外部调用操作,请使用this.send
this.send('onAccept');
有关send
和sendAction
的更多信息,请访问:https://medium.com/ember-titbits/ember-send-and-sendaction-5e6ac9c80841