lajuma
lajuma

Reputation: 494

this is undefined in controller (ember, 3.x)

Run into a problem with ember (v.3.x), and cannot figure out why. I did not find anything (that worked in my case) in the docs nor here.

So, here's the problem: this returns undefined in my controller inside the computed property (undefined.get('filter')). The rest of my function works, so I did not put it in here.

// in dic.js (controller):
export default Controller.extend({
  filter: '',
  filteredTerms: computed('filter', () => {
     const x = this.get('filter');
     // ...
}),

The corresponding input field:

// in dic.hbs
{{input value=filter}}

In my route I just return the model, which should be filtered by that function.

Upvotes: 3

Views: 674

Answers (1)

Lux
Lux

Reputation: 18240

The answer is simple: don't use an arrow function for the computed. This should work:

filteredTerms: computed('filter', function () {
  const x = this.get('filter');
  // ...

This is the fundamental difference between normal functions and arrow functions. Arrow functions dont have their own this-context. this inside an arrow function is always the same as outside. And well, outside in this case it literally outside the object, so the global context. So you get window/undefined depending if you're in strict mode or not.

So general rule:

  • use an arrow function if you want access to the outer this or dont use this at all
  • use a normal function when you want a this-context

Upvotes: 6

Related Questions