Search code examples
javascriptarraysember.jscomputed-properties

EmberJS computed property based on array not working


I have an EmberJS controller that has the following computed property:

hasSelectedRequirements: Ember.computed('selectedRequirements.[]', function()    {
    console.log("this should get printed but it doesn't");
    return this.get('selectedRequirements').length > 0;
}),

which sets a boolean flag I am using in a template to conditionally display html.

I also have a button, that, when clicked, takes the form data and pushes an element onto the selectedRequirements array by calling the addRequirement action

actions: {
    addRequirement() {
        ...
        // extract data from form and create the requirement variable

        var selectedRequirements = this.get('selectedRequirements');
        selectedRequirements.push(requirement);
        this.set('selectedRequirements', selectedRequirements);

        console.log(this.get('selectedRequirements')); // does print as expected
    }
}

If I change the addRequirement function to this instead, then the hasSelectedRequirements computed property's function handler is run as expected, and the console.log statement works:

actions: {
    addRequirement() {
        ...
        // extract data from form and create the requirement variable

        var selectedRequirements = this.get('selectedRequirements');
        selectedRequirements.push(requirement);

        // create a new, local array
        var arr = new Array();
        arr.push(1);

        this.set('selectedRequirements', arr);

        console.log(this.get('selectedRequirements')); // does print as expected
    }
}

It seems as though Ember's computed properties rely upon the array that is being observed being a completely different array?

The problem is that the computed property is not recognizing that an element was added to the selectedRequirements array, and the computed property function never gets called (the console.log statement never runs). Why does the computed property not recognize that the selectedRequirements array has been modified and how can I fix the computed property code?


Solution

  • Use pushObject like this.get('selectedRequirements').pushObject(obj);