0

I am unable to access the EmberArray by index in the template. This is part of my route

model(){
  return RSVP.hash({
    games: this.store.findAll('game')
  })
}

And this is part of the template

<div>
  First game: {{model.games.[0].name}}
</div>

There is no output that is rendered. Although if I iterate over it using

{{#each model.games as |game|}}
  <div>{{game.name}}</div>
{{/each}}

This works fine. Any idea what I might be doing wrong, or what I should do different ?

Thanks

3 Answers 3

2

You can use firstObject method.

{{model.games.firstObject.name}}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, yes, that worked. And any idea how I can access the second element ?
You can create computed property and use it in template. secondGame: Ember.computed('model.games', function { return this.get('model.games').objectAt(1); }
Thanks! Yes, I have done this for now. Seemed like the cleanest way.
2

If you don't want to iterate over all of items and if you don't mind composing a bit of logic dierctly in the template, ember-composable-helpers addon might come useful, for example accessing a concrete item in a given array using object-at, from the docs:

Returns the object at the given index of an array.

Notation:

{{object-at index array}}

which (in a case you want to show a name of the second item) would be:

{{object-at 1 model.games}}

2 Comments

This looks interesting thanks. And how would I access a property on the given object ? {{(object-at 1 model.games).name}} ?
You could use the get helper. {{get (object-at 1 model.games) 'name'}} Nothing limits you in composing template helpers altogether. Take a look at another example from the ember-composable-helpers docs: {{take 5 (sort-by "lastName" "firstName" (filter-by "active" array))}}. Hence the name composable :) Isn't that beautiful? :)
1

You can create a helper. Something like this:

// app/helpers/array-index.js
import Ember from 'ember';

export default Ember.Helper.helper(function ([array, index]) {
  return array !== undefined && array[index] !== undefined ? array[index] : undefined;
});

Use it together with get:

{{get (array-index model.games 1) 'name'}}

P.S. As we are talking about collection returned from Ember Data, that's may be not a pure js array, but something like ArrayProxy. In this case you probably need to use it's method objectAt:

// app/helpers/array-index.js
import Ember from 'ember';

export default Ember.Helper.helper(function ([array, index]) {
  return array && array.objectAt ? array.objectAt(index) : (array && array[index]);
});

1 Comment

Oh this looks great! Thanks, might give this a shot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.