Unable to access component property with 'this.get'

I have a nested component that is stubbornly refusing to give me access to a property in the component.js file and I don’t know why.

The component is a few layers down as follows:

{{component-1 myProperty=aSecondModel}}
--{{component-2 myProperty=myProperty}}
---{{component-3 myProperty=myProperty}}
----{{component-4 myProperty=myProperty}}

Note that the above components also have other properties being passed through them but I hope that illustrates the structure.

In the template of component 4 I have access to myProperty and I can use it (for example, with an {{#each}} helper but I would like to perform some tasks on it within the component.js

I thought I could access it with

this.get(‘myProperty’)

However I keep getting ‘cannot read property ‘get’ of undefined’ errors. I get this whether I try to add it as a variable or try to add a new property to Component.extend. I can’t even console.log(this.get('myProperty)) without getting the error.

What am I missing in trying to access this piece of information?

I believe the error is saying that this is undefined? could you share he function that you’re doing the console.log in? I wonder if it’s a js scopeing / context issue.

I haven’t actually got as far as using anything in a function yet as I can’t access the myProperty. So the error appears if I try and assign via either of the following:

import Component from '@ember/component';

let item = this.get('myProperty') //error

export default Component.extend({
 item: this.get('myProperty), //error

});

I haven’t been able to check the context because console.log(this) gives me the same error!

so, the whole file doesn’t have access to the component instance. the file defines a class that represents component, and within an instance of that component, you can access this

try this:

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

export default Component.extend({
 item: computed('myProperty', function() {
    console.log(this);

    return this.get('myPproperty');
    // or if you're using ember 3 (maybe 3.1?)
    return this.myProperty;
 });
});

Checkout these docs: https://guides.emberjs.com/release/object-model/computed-properties/

2 Likes

Yeah that’s absolutely correct.

Thanks for expanded explanation, it makes sense when you realise it is an instance of a class.

1 Like