简体   繁体   中英

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.

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.

And this behavior seems necessary, because component events belong outside of the 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?

This seems to be a poorly documented part of controllers in 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

this.send('onAccept');

More information on send and sendAction can be found here: https://medium.com/ember-titbits/ember-send-and-sendaction-5e6ac9c80841

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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