简体   繁体   English

Ember.js中this的基本用法

[英]Basic use of `this` in Ember.js

I'm fairly adept in Javascript but I'm having a hard time understanding how Ember is handling the this context in certain scenarios. 我相当精通Java语言,但是很难理解Ember在某些情况下如何处理this上下文。

I have a component controller: 我有一个组件控制器:

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!')
    }
  }
}

Every time I run this though, I get the following error: 但是,每次运行此命令时,都会出现以下错误:

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

This seems to always happen when I have a method outside of the actions hash that needs to access a function inside the actions hash, or the other way around. 这似乎当我有以外的方法经常发生actions哈希需要访问内部的功能actions的散列, 或者反过来。

And this behavior seems necessary, because component events belong outside of the actions hash . 而且这种行为似乎是必需的,因为组件事件属于actions hash之外

So how am I supposed to have event methods outside of the actions hash but still be able to call methods that belong inside of the actions hash? 那么,我应该如何在actions哈希之外具有事件方法,但仍然能够调用在actions哈希内部属于的方法呢?

This seems to be a poorly documented part of controllers in Ember. 在Ember中,这似乎是控制器中记录很少的一部分。 Maybe I am just missing something here. 也许我只是在这里想念东西。 Any help is greatly appreciated. 任何帮助是极大的赞赏。

To call an action from outside the actions hash, use this.send 要从actions哈希之外调用动作,请使用this.send

this.send('onAccept');

More information on send and sendAction can be found here: https://medium.com/ember-titbits/ember-send-and-sendaction-5e6ac9c80841 有关sendsendAction更多信息, send参见以下网址https : sendAction

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM