Riccardo Bartoli
Riccardo Bartoli

Reputation: 569

Accessing ArrayController elements using needs

I've got the following 2 controllers:

controllers/student/index.js

import Ember from 'ember';

export default Ember.ObjectController.extend({
    hasDebt: function(){
        var totalCredit = this.get('totalCredit');
        var totalCreditSpent = this.get('totalCreditSpent');

        if (totalCreditSpent > totalCredit) 
        {
            return true;
        }

        return false;
    }.property('payments.@each', 'lessons.@each'),
});

controllers/students.js

import Ember from 'ember';

export default Ember.ArrayController.extend({
    itemController: 'student/index',
    sortProperties: ['fullName'],
    sortAscending: true,

    debts: function(){
        var allDebts = [];
        var totalDebts = 0;

        this.forEach(function(student){
            if (student.get('hasDebt'))
            {
                allDebts.push({
                    name: student.get('fullName'), 
                    amount: student.get('availableCredit')
                });

                totalDebts += student.get('availableCredit');
            }
        });

        return {'all': allDebts, 'total': totalDebts};
    }.property('[email protected]', '[email protected]'),
});

And everything is working as expected. I'm able to access the hasDebt property of each element through the itemController.

Now I'd like to show the debts in a dashboard in the IndexRoute, so I've created the following additional controller, hoping to be able to access the StudentsController by using needs:

controllers/index.js

import Ember from 'ember';

export default Ember.Controller.extend({
    needs: ['students'],

    debts: function(){
        var debts = [];

        console.log( this.get('controllers.students.debts') );

        this.get('controllers.students').forEach(function(student){
            console.log('student');
        });

        return debts;
    }.property(''),
});

I seem unable to access the StudentsController and any of its properties.

What am I doing wrong?

Upvotes: 0

Views: 79

Answers (1)

Ben Murden
Ben Murden

Reputation: 630

I believe that a computed property must observe a property in order to ever be populated. In your example:

controllers/index.js

export default Ember.Controller.extend({
  needs: ['students'],
  students: Em.computed.alias('controllers.students'),
  debts: function() {
    ...
  }.property('students.debts')
});

In this example I also made it a little easier to use Students by providing a Computed Alias mapped to students in the controller.

Debugging

It's also very handy to use the browser's console when debugging. Try running something like the following and see what comes back.

App.__container__.lookup('controller:index').get('students')

This assumes your application exists under the App namespace.

Upvotes: 0

Related Questions