Tair
Tair

Reputation: 3809

How to get current model for a route from a controller or a view?

I want to implement item-list/item-detail pattern in Ember, but the nuance is that the detail view must appear next to the selected item. E.g:

<ul>
    <li><div>Post 1<div></li>
    <li><div>Post 2<div></li>
    <li><div>Post 3<div></li>
    <li>
        <div>Post 4<div>
        <div>
            <ul>
                <li>Comment 1</li>
                <li>Comment 2</li>
                <li>Comment 3</li>
            </ul>
        </div>
    </li>
    <li><div>Post 5<div></li>
</ul>

The Handlebars template I tried is:

<script type='text/x-handlebars' data-template-name='posts'>
    <ul>
        {{#each model}}
            {{#linkTo 'post' this}}
                <div>{{title}}</div>
            {{/linkTo}}
            {{#if isSelected}} <!-- How to implement isSelected ? -->
                <div>{{!-- render selected post's comments --}}</div>
            {{/if}}
        {{/each}}
    </ul>
</script>

I tried this in controller:

App.PostController = Em.ObjectController.extend({
    isSelected: function() {
        return this.get('content.id') === /* what to put here? */;
    }
});

What I'm stuck with is how to implement isSelected in 'Ember'-way? Am I going in right direction?

Upvotes: 2

Views: 4939

Answers (1)

Mike Grassotti
Mike Grassotti

Reputation: 19050

You are on the right track. The trick is to use a different controller to wrap products in the item-list vs. the item-detail. So start by specifying that the handlebars {{each}} helper should wrap each entry in a ListedProductController

{{#each model itemController="listedProduct"}}

Now define ListedProductController, adding the isSelected function you'd been writing. Now it can reference the singleton ProductController via the needs array, comparing the product that was set by the router to the listed product.

App.ProductController = Ember.ObjectController.extend({});
App.ListedProductController = Ember.ObjectController.extend({
  needs: ['product'],
  isSelected: function() {
    return this.get('content.id') === this.get('controllers.product.id');
  }.property('content.id', 'controllers.product.id')
});

I've posted a working example here: http://jsbin.com/odobat/2/edit

Upvotes: 3

Related Questions