handlebears
handlebears

Reputation: 2276

Why do I get 'this is undefined' in my Octane component methods?

I'm writing some Octane-style components in Ember v3.13, together with the {{did-insert}} ember-render-modifier. However, when the function tied to did-insert is called, I get TypeError: this is undefined. What am I doing wrong?

Here's my component template:

<div class="cardhost-monaco-container" {{did-insert this.renderEditor}}></div>

And here's the component's JavaScript class:

import Component from '@glimmer/component';


export default class CodeEditor extends Component {
  renderEditor(el) {
    console.log(this.args.code)
  }
}

Upvotes: 2

Views: 839

Answers (1)

handlebears
handlebears

Reputation: 2276

Methods that are used as actions in templates need to be decorated with @action to have correct this-context:

import Component from '@glimmer/component';
import { action } from '@ember/object';

export default class CodeEditor extends Component {
  @action
  renderEditor(el) {
    console.log(this.args.code)
  }
}

The action decorator binds the component context to the method. This is described in more detail in the API docs for action.

Upvotes: 9

Related Questions