Bennidhamma
Bennidhamma

Reputation: 770

How to load an object from an id in an Ember View?

I'm trying to build a view to display a user card, from their id. So ideally my calling handlebars would look something like:

<p>{{view App.UserThumb authorId}}
{{comment}}</p>

And then in my UserThumb view, I'd like to be able to load a model, in some sort of setup method or model function, sort of how I'm using controllers:

App.UserThumb = Ember.View.extend({
  model: function(view, authorId) {
    User.find(authorId, function(user) { view.set('content', user); } );
  }
}

Can anyone help me understand the 'right' or at least a workable way to do this? Worst case I can go and create the objects first, but I'd like to just keep the id around for a bit first, unless that is just totally at odds with the philosphy of Ember.

Upvotes: 0

Views: 82

Answers (2)

Mudassir Ali
Mudassir Ali

Reputation: 8041

This should do

{{#each id in listOfIds}}
  {{view App.UserThumb idBinding="id"}}
{{/each}}

App.UserThumb = Ember.View.extend({
  didInsertElement: function() {
    var authorId = this.get('id');
    User.find(authorId, function(user) { view.set('content', user); } );
  }
}

Only after the view is inserted the didInsertElement hook gets executed which gets the required user

Upvotes: 1

intuitivepixel
intuitivepixel

Reputation: 23322

The model hook you re using in your View is only available inside a Route. The model hook can be used to setup the model for a controller.

See here the docs for more info on that.

In the spirit of DRY (Dont Repeat Yourself) I'd like to link to this great SO answer that will help setup a functional application, the ember way.

Hope it helps

Upvotes: 0

Related Questions