jrabary
jrabary

Reputation: 2441

Unable to set elementId of a view into list content id

I have a view that renders a list elements using the following template :

   {{#each item in controller}}
       {{view App.ItemView}}        
    {{/each}}

I need the id of each item the be the id of corresponding itemView. Here is my first attempt but it doesn't work :

App.ItemView = Ember.View.extend({
    elementId: Ember.computed(function(){
        return this.getPath('item.id');
    }),
    templateName: 'item'
});

What I'm doing wrong ?

You can find a jsfiddle illustrating my problem here http://jsfiddle.net/jrabary/vk4Ze/

Upvotes: 3

Views: 1230

Answers (2)

user718147
user718147

Reputation:

The above answers helped me. In the end I wanted to set the ID attribute of the view's wrapping tag specifically to be the model's ID. I found you can use the view's didInsertElement hook to achieve that by accessing the currently-rendered element's context with this.get('context').get('anyProperty') and the DOM element itself (as jQuery object) with this.$(). Seems long-winded but couldn't see the cleaner way.

App.MyView = Ember.View.extend({
    templateName: 'MyTemplate',
    didInsertElement: function(e){
        this.$().attr('id', this.get('context').get('id'));
    }
});

Upvotes: 2

Mike Aski
Mike Aski

Reputation: 9236

At the moment the view need to compute the elementId property, item is not yet set, so here the problems are starting...

If you want to set the id once the item is available, you will have to allow Ember to retrieve the DOM element to alter... That means Ember has to set the element's id! In other words, it is impossible as of today, as Ember uses elements id to keep references on its DOM owned/controlled elements.

Nevertheless, the view has the displayed item bound to it, so you can retrieve the item later. What is exactly you underlying need?

EDIT

Here is a sample customizing element's class according to item's id: http://jsfiddle.net/MikeAski/ZAHxm/

Upvotes: 2

Related Questions