Computed property on fat arrow functions


#1

I’m just wondering why fat arrow functions don’t work with computed properties. For instance:

export default Ember.Component.extend({
    title: null,
    items: null,
    classNames: ['menu-section'],
    hasTitle: () => {
        return this.get('title').length > 0;
    }.property('title')
});

Will result in the following error:

Uncaught TypeError: Cannot read property ‘get’ of undefined

I’m curious as to why this would fail? I understand that it doesn’t include the lexical ‘this’ property, but how come regular functions do? It seems like both would result in undefined. Or, is there some special magic happening in Babel that I don’t know about? :smile:


#2

Because the context you’re passing in is the “top-level” context, which doesn’t have a “this”. You can only go up the chain so far.


#3

Still learning the new ES stuff myself, but I think you could install the ember-computed-decorators addon to then do something like:

import Ember from 'ember';
import computed from 'ember-computed-decorators';

export default Ember.Component.extend({
    title: null,
    items: null,
    classNames: ['menu-section'],

    @computed('title')
    hasTitle() {
        return this.get('title').length > 0;
    }
});

#4

We still get this question occasionally on slack, so adding a link to a blog that explains the reason behind why it doesn’t work & solutions in detail,