mehulkar
mehulkar

Reputation: 4964

Ember.js: How to stay in Leaf Route on model change, when link-to goes to parent resource

I have a list of posts, with a nested summary and full route.:

App.Router.map(function() {
  this.resource('post', {path: ':post_id'}, function() {
    this.route('summary', {path: '/'});
    this.route('full');
  });
});

The summary route is at path: /, so when I {{#link-to 'post' somePost}}, it arrives in post.summary.

When I change the model, i.e. route to someOtherPost, I would like to stay in the current leaf route (either summary or full).

How do I do this? I tried willTransition, but I'm not sure how to check if the model changed:

Here's a JSBin with what I have so far: http://emberjs.jsbin.com/benot/2/edit?js,output

Upvotes: 1

Views: 129

Answers (1)

Kingpin2k
Kingpin2k

Reputation: 47367

This is a great use case for a dynamic link-to.

link-to Code

App.ApplicationController = Em.ArrayController.extend({
  postLink: 'post'
});

Template

{{#each item in controller}}
  <li>{{#link-to postLink item}}{{item.title}}{{/link-to}}</li>
{{/each}}

You can send an action from each child route, and it will go up the router (http://emberjs.com/guides/templates/actions/) until caught. At the parent route you can change the dynamic value of the link-to and bam, you're good to go.

Route Code

App.PostSummaryRoute = Em.Route.extend({
  actions:{
    didTransition: function(){
      this.send('swapLink', 'post.summary');
    }
  }
});

App.PostFullRoute = Em.Route.extend({
  actions:{
    didTransition: function(){
      this.send('swapLink', 'post.full');
    }
  }
});


App.ApplicationRoute = Ember.Route.extend({
  model: function() {
    return [
      App.Post.create({id: '1', title: 'Foo', body: 'Lorem'}),
      App.Post.create({id: '2', title: 'Bar', body: 'Ipsum'})
    ];
  },
  actions: {
    swapLink: function(newLink){
      console.log('swapLink ' + newLink);
      this.controller.set('postLink', newLink);
    }
  }
});

http://emberjs.jsbin.com/dekokafu/1/edit

Upvotes: 2

Related Questions