2
votes

I am having trouble displaying computed properties in my view

I am learning EmberJS for less than a week. Different tutorials have different coding styles, which is very confusing, so I am following http://coding.smashingmagazine.com/2013/11/07/an-in-depth-introduction-to-ember-js/
I saw some similar posts on stackoverflow but the code is too complex for me to understand, and my question is very basic and no post I have seen just answers that bare basic.

Here is my 'users' handlebars template. It is written in index.html. I am putting only the handlebars script part.

<script type="text/x-handlebars" id="users">
    <div>

    <ul class="users-listing">
        {{#each user in controller}}
            <li>{{user.name}} ..... {{user.id}} ..... {{user.NameWithId}}</li>
        {{else}}
            <li>no users… :-(</li>
        {{/each}}
    </ul>

    Total users: {{usersCount}}

    </div>


</script>

Here is my model

App.ApplicationAdapter = DS.FixtureAdapter;

App.User = DS.Model.extend({
  name         : DS.attr(),
  email        : DS.attr(),
  bio          : DS.attr(),
  avatarUrl    : DS.attr(),
  creationDate : DS.attr()
});

Here is my Controller

App.UsersController = Ember.ArrayController.extend({
  sortProperties: ['id'],
  sortAscending: true, // false = descending

  usersCount: function(){
    return this.get('model.length');
  }.property('@each'),

  NameWithId: function() {
    return this.get('id') + ' -> ' + this.get('name');
  }.property('id', 'name')
});

After executing the script, I can see ID and name, but in the place of NameWithId I get just blank Even my web console in Firefox shows nothing

In my template I changed

user.NameWithId

to

user.get('NameWithId')

Now I get Parse Error: Expecting 'ID', got 'INVALID'


Using:
jQuery 1.10.2
handlebars 1.0.0
Ember 1.0.0
EmberData 1.0.0-beta3

2

2 Answers

2
votes

The computed property should be on the model, not the controller. It's a property of a single user instance, whereas your controller is an ArrayController, for many user instances (hence the @each in the previous computed property declaration).

3
votes

You can place it on the model like sevenseacat said, or you can use an itemController which will wrap up each item in the array with a controller, and that's where you would place this property.

App.UsersController = Ember.ArrayController.extend({
   itemController: 'user'
})

App.UserController = Ember.ObjectController.extend({
  NameWithId: function() {
    return this.get('id') + ' -> ' + this.get('name');
  }.property('id', 'name')
});