Ember: Reuse nested route in different parents - ember.js

I wanted to know how to reuse a nested route in different parent route.
For example:
Template routeA:
{{outlet}} -> routeX
Template routeB:
{{outlet}} -> routeX
Router.map(function() {
this.route('routeA', function(){
this.route('routeX', {resetNamespace:true});
});
this.route('routeB', function(){
this.route('routeX', {resetNamespace:true});
});
})
I need to use {{link-to 'routeX'}} to show routeX inside the current parent.
In the example always shows the routeB when I use {{link-to 'routeX'}}
I have 2 aproax to solution:
1) Put 1 child route in routeA and other in routeB:
Router.map(function() {
this.route('routeA', function(){
this.route('routeX');
});
this.route('routeB', function(){
this.route('routeX');
});
})
and use {{link-to 'routeA.routeX'}} and {{link-to 'routeB.routeX'}}
but in this aproax I have a duplicate code.
2)
router.map(function() {
this.route('*wildcard', function(){
this.route('routeX', {resetNamespace:true});
});
})
this option works but in the url appear "undefined" http://...undefined/routeX
Any idea?
Thanks

If possible, I recommend using either a component or mixin to share whatever code or functionality you need between those two similar routes.
That would look something like this
export default Ember.Mixin.create({
model() {
return Ember.Object.create({title: 'Awesome'})
}
});
and then use it in your route like so,
import ReUseMixin from '../../mixins/re-use'
export default Ember.Route.extend(ReUseMixin,{
or by defining your component, as lets say re-use.hbs and re-use.js
you can just use that in routeA/routeX and routeB/routeX as
{{re-use}}
Here is a link to an ember twiddle, that demonstrates what I would recommend, hopefully that can provide you with a solution.

Related

Call Router.generate from a helper

I need to generate the url for given route from a helper.
How to generate url for a route in Ember.js pointed me to use the generate function. And yes it works as i need (Checked the functionality by making application route global). But i am not sure how to call it from inside a helper.
You were in a good direction, so you mainly solved this problem. :) There are two type of helper in Ember a simple function helper and the Class Based Helpers. We will use a Class Based Helper in this case.
As you have seen in your linked example, we need access to the main Router. We can do this with Ember.getOwner(this).lookup('router:main'). (Ember.getOwner() exists from v2.3, before v2.3 use this.container.lookup('router:main'))
For example, you have this map in your router.js:
Router.map(function() {
this.route('about');
this.route('posts', function() {
this.route('post', {path: '/:post_id'});
});
});
And if you create a helper for example with the name of url-for your template could contain these lines:
{{url-for 'about'}}
{{url-for 'posts'}}
{{url-for 'posts.post' 2}}
And your Class Based Helper could be the following:
// app/helpers/url-for.js
import Ember from 'ember';
export default Ember.Helper.extend({
router: Ember.computed(function() {
return Ember.getOwner(this).lookup('router:main');
}),
compute([routeName, ...routeParams]) {
let router = this.get('router');
return Ember.isEmpty(routeParams) ?
router.generate(routeName) : router.generate(routeName, routeParams[0]);
}
});
Demo on Ember Twiddle

How are ember links to reused nested routes defined using link-to?

Using the example route defined below how can a link be defined to /post/123/comments?
Router.map(function() {
this.route('post', { path: '/post/:post_id' }, function() {
this.route('edit');
this.route('comments', { resetNamespace: true }, function() {
this.route('new');
});
});
this.route('comments');
});
Since resetNamespace: true is set on comments, the route post.comments does not exist. Otherwise the following would work.
{{#link-to "post.comments" "123"}}Link{{/link-to}}
When trying to link to news using the comment id, the error More context objects were passed than there are dynamic segments for the route: comments occurs.
{{#link-to "comments" "123"}}Link{{/link-to}}
An example of the second case can be seen here: https://ember-twiddle.com/d9f3b5e692573c80e803
Thanks to locks for pointing me in the direction. The specific issue is how to reuse as much of the route and template as possible for different paths.
router.js:
Router.map(function() {
this.route('post', { path: '/post/:post_id' }, function() {
this.route('edit');
this.route('comments', function() {
this.route('new');
});
});
this.route('comments');
});
routes/post/comments.js:
import Comments from '../comments';
export default Comments.extend({
renderTemplate() {
this.render('comments');
}
});
This will extend the existing comments route to reuse the model and actions defined in the base route. The renderTemplate is still necessary to load the comments template instead of the post.comments template.
Since you're resetting the namespace, you are effectively overriding one of the comments route with the other. You're doing something akin to
obj['comments'] = firstRoute;
obj['comments'] = secondRoute;
Route names need to be unique, which they would be if you didn't reset the namespace, as well as the path. If two routes have the /foobar path, then Ember won't know which one to transition to.
If what you want is to reuse parts from other routes, there are ways to do that.

Can I force 'active' class on a {{link-to}} helper?

Here is possibly an edge case for how ember adds the 'active' class on a link to helper.
I have my current router set up like so:
import Ember from 'ember';
var Router = Ember.Router.extend({
location: PortalDevENV.locationType
});
Router.map(function() {
this.resource('portal', function() {
this.route('admin');
this.resource('placements', function() {
this.route('import-debtors');
this.resource('add-debtor', function() {
this.route('debtor-form');
});
this.route('view-debtors');
});
this.resource('debtor', {path: 'placements/view-debtors/debtor/:debtor_id'}, function() {
this.route('agent-notes');
this.route('transactions');
});
});
});
export default Router;
notice how I have a resource called "debtor" that- while it is being rendering into the portal template- i still need it to appear (in terms of the URL) to be a child of the "view-debtors" route... which, in reality, is nested deeper within a separate set of templates.
This structure seems to be working fine, but it is breaking my breadcrumb-style navigation.
When moving into the "debtor" page.. i still want "view-debtors" {{link-to}} helper to get the 'active' class from ember... along with the {{link-to}}'s that lead up to the "view-debtors".
Is this possible to do by calling some functions in my routes... or some other way?
It doesn't seem to be a common ember convention... but then again perhaps Ember actually does work in this way and I did something else that broke it? Take a look and see if my set up is correct.
You should be able to bind the active class to a computed property. Assuming the {{link-to}} you are referring to is in your application.hbs template, you could do something like this:
// templates/applictaion.hbs
{{#link-to "view-debtors" class="isDebtorsRoute:active"}}View Debtors{{/link-to}}
// controllers/application.js
export default Ember.Controller.extend({
isDebtorsRoute: function() {
// use this.get('currentRouteName') or this.get('currentPath')
}.property('currentPath')
})
EDIT: Here is a jsbin example http://emberjs.jsbin.com/wuhor/1/edit?html,css,js,output

Ember router naming conventions

I have a need for deep nesting some routes in ember, I have something like this.
this.resource('wizards', {
path: '/wizards'
}, function() {
this.resource('wizards.google', {
path: '/google'
}, function() {
this.resource('wizards.google.register', {
path: '/register'
}, function() {
this.route('step1');
this.route('step2');
this.route('step3');
this.route('summary');
});
});
});
What I was expecting was as structure like this:
url /wizards/google/register/step1
route name wizards.google.register.step1
route Wizards.Google.Register.Step1Route
Controller Wizards.Google.Register.Step1Controller
template wizards/google/register/step1
but I got this:
url /wizards/google/register/step1 //as expected
route name wizards.google.register.step1 //as expected
route WizardsGoogle.Register.Step1Route
Controller WizardsGoogle.Register.Step1Controller
template wizards/google.register.step1
What I don't get is when does ember stop using capitalization (WizardsGoogle) and start using namespaces (WizardsGoogle.Register). The seemingly inconsistency confuses me. I would have expected either of them.
I met the same things with deep nested resources. Although I didn't know how this happens, what I can tell is that you can always use CapitalizedNestedRoute without namespace, and Ember can recognize it. Although in Ember Inspector it displays "WizardsGoogle.Register.Step1Route".
In your example I defined such route:
App = Em.Application.create();
App.Router.map(function() {
this.resource('wizards', function() {
this.resource('wizards.google', function() {
this.resource('wizards.google.register', function() {
this.route('step1');
this.route('step2');
this.route('step3');
});
});
});
});
App.IndexRoute = Em.Route.extend({
beforeModel: function() {
// Transition to step1 route
this.transitionTo('wizards.google.register.step1');
}
});
App.WizardsGoogleRegisterStep1Route = Em.Route.extend({
model: function() {
// You can see this alert when you enter index page.
alert('a');
}
});
In this example the app will transition to WizardsGoogleRegisterStep1Route with no problem. And if you use container to find route like this:
App.__container__.lookup('route:wizards.google.register.step1').constructor
It will also display App.WizardsGoogleRegisterStep1Route. It's the same as Ember Guide describes. http://emberjs.com/guides/routing/defining-your-routes/#toc_nested-resources And Ember Guide doesn't introduce namespace route.
So I think it's better to according to what Ember Guide suggests (always use CapitalizedNestedRoute). And in my opinion it's easier to define CapitalizedNestedRoute than nested.namespace.route.
Finally, if you really want to use namespace route/controller/template, you can have a look at Ember.DefaultResolver. Check the API to learn how to extend it so container can lookup modules by your own rules.
Routes are "namespaced" inside resources. And resources uses what you call capitalization, where they sort of define a namespace (for routes to use).
So this set of routes:
App.Router.map(function() {
this.resource('posts', function() {
this.route('new');
this.route('old');
this.route('edit');
this.route('whatever');
});
});
Would result in routes with the following name:
PostsRoute
PostsNewRoute
PostsOldRoute
PostsEditRoute
PostsWhateverRoute
Whereas, the following set of routes:
App.Router.map(function() {
this.resource('posts', function() {
this.resource('photos');
this.resource('comments');
this.resource('likes');
this.resource('teets');
});
});
Would result in route with the following names:
PostsRoute
PhotosRoute
CommentsRoute
LikesRoute
TeetsRoute
Also note, that resources within resources don't get "namespaced" to the "parent" resource, so you'll always ever have the form:
{CapitalizedResourceName}Route // for resources
{CapitalizedParentResourceName}{RouteName}Route // for routes
I hope this helps you!

Idiomatic Emberjs for nested routes but non-nested templates

This is a follow-up from Understanding Ember routes.
Master/detail views are great but I'm trying to have a a hierarchical URL route without nesting their templates. However, I still need access to the parent model for things like breadcrumb links and other references.
So /users/1/posts should display a list of posts for user 1. And /users/1/posts/1 should display post 1 for user 1, but it shouldn't render inside the user template's {{outlet}}. Instead, it should completely replace the user template. However, I still need access to the current user in the post template so I can link back to the user, show the user's name, etc.
First I tried something like this (Method #1):
App.Router.map(function() {
this.resource('user', { path: '/users/:user_id' }, function() {
this.resource('posts', function() {
this.resource('post', { path: '/:post_id' });
});
});
});
...
App.PostRoute = Ember.Route.extend({
model: function(params) {
return App.Post.find(params.post_id);
},
renderTemplate: function() {
this.render('post', {
into: 'application'
});
}
});
This replaced the the user template with the post one, as expected. But when I click the browser's back button the user template doesn't render again. Apparently the post view is destroyed but the parent view is not re-inserted. There are a few questions on here that mention this.
I then got it to work with something like this (Method #2):
App.Router.map(function() {
this.resource('user', { path: '/users/:user_id' }, function() {
this.resource('posts');
this.resource('post', { path: '/users/:user_id/posts' }, function() {
this.resource('post.index', { path: '/:post_id' });
});
});
...
App.PostRoute = Ember.Route.extend({
model: function(params) {
return App.User.find(params.user_id);
},
setupController: function(controller, model) {
controller.set('user', model);
}
});
App.VideoIndexRoute = Ember.Route.extend({
model: function(params) {
return App.Post.find(params.post_id);
}
});
App.PostIndexController = Ember.ObjectController.extend({
needs: 'post'
});
But this seems a bit hacky to me and not very DRY.
First, I need to retrieve the User again in the PostRoute and add it as an ad-hoc variable to the PostController (this wouldn't be necessary if the routes were properly nested and I could just set a needs: 'user' property in the PostController). In addition, this may or may not have an impact on the back-end depending on the adapter implementation of ember-data or whatever technology is used to retrieve the data from the server (i.e. it may cause an unnecessary second call to load User).
I also need an additional `PostIndexController' declaration just to add that new dependency, which is not a big deal.
Another thing that doesn't feel right is that /users/:user_id/posts appears twice in the router configuration (one nested, one not).
I can deal with these issues and it does work but i guess that, overall, it seems forced and not as graceful. I'm wondering if I'm missing some obvious configuration that will let me do this with regular nested routes or if someone has a recommendation for a more "Ember.js way" of doing this.
I should mention that regardless of the technical merits of Method #2, it took me quite a while to figure out how to make it work. It took a lot of searching, reading, experimenting, debugging, etc. to find just the right combination of route definitions. I would imagine that this is not a very unique use-case and it should be very straightforward for a user to set up something like this without spending hours of trial and error. I'll be happy to write up some tips for this in the Ember.js documentation if it ends up being the right approach.
Update:
Thanks to #spullen for clarifying this. My case was not as straightforward as the example because some sub-routes need nested templates and some don't, but the answer helped me figure it out. My final implementation looks something like this:
App.Router.map(function() {
this.resource('users', { path: '/users/:user_id' }, function() {
this.resource('users.index', { path: '' }, function() {
this.resource('posts')
});
this.resource('post', { path: '/posts/:post_id' }, function() {
this.resource('comments', function() {
this.resource('comment', { path: '/:comment_id' });
});
});
});
});
So now posts renders under the users template but post replaces everything. comments then renders under post and comment, in turn, renders under comments.
All of them are sub-routes of users so the user model is accessible to all of them without acrobatics, by doing this.modelFor('users') in each Route where needed.
So the templates look like this:
users
|- posts
post
|- comments
|-comment
I don't know why the { path: '' } is needed for the users.index resource definition but if I take it out Ember doesn't find the users route. I would love to get rid of that last vestige.
You could define the parent template to just display the outlet and have an index route which will get displayed inside that. Then for the nested resource you can do the same thing.
<script type="text/x-handlebars" data-template-name="user">
{{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="user/index">
<h2>user/index</h2>
</script>
<script type="text/x-handlebars" data-template-name="posts">
{{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="posts/index">
<h2>posts/index</h2>
</script>
That way it won't be a master/detail.
The router would be:
App.Router.map(function() {
this.resource('user', function() {
this.resource('posts', function() { });
});
});
Then if you need to get information about the parent you can use modelFor. So if you were in posts, you could do this.modelFor('user');
Here's a jsbin that demonstrates this.
Hope this is helpful.