Ember.js - swap an embedded resource from any route

I have routes with nested dynamic segments, for example /:locale/products/:product_id/items/:item_id , etc. I want to relocate in action on a locale route. I do not want to switch to the base route /:locale when changing the locale.

Locale route action:

 actions: { localeChanged: function(locale) { var route = this.controllerFor('application').get('currentRouteName'); this.transitionTo(route, locale); } } 

This only works when I'm not deeply nested. I would like to avoid implementing the localeChanged action on each route in order to provide the exact models needed for this route.

Update 1 - Dirty Solution:

 actions: { localeChanged: function(locale) { var routes = this.router.router.currentHandlerInfos; var models = []; for (var i = 0; i < routes.length; i++) { var params = routes[i].params; for (var param in params) { if (params.hasOwnProperty(param)) { models.push(param === 'locale' ? locale : params[param]); } } } var args = models.slice(); var currentRouteName = this.controllerFor('application').get('currentRouteName'); args.unshift(currentRouteName); this.transitionTo.apply(this, args); } } 

I say dirty because iterating over this.router.router.currentHandlerInfos seems to be error prone. Is there a better way?

+7
javascript url-routing single-page-application
source share
1 answer

You can create a baseRoute that will add this action. Then all your routes can inherit from this base route. You only need to write the code once, and it is divided along all routes. For example.

 App.BaseRoute = Ember.Route.extend({ actions: { localeChanged: function(locale) { var routes = this.router.router.currentHandlerInfos; var models = []; for (var i = 0; i < routes.length; i++) { var params = routes[i].params; for (var param in params) { if (params.hasOwnProperty(param)) { models.push(param === 'locale' ? locale : params[param]); } } } var args = models.slice(); var currentRouteName = this.controllerFor('application').get('currentRouteName'); args.unshift(currentRouteName); this.transitionTo.apply(this, args); } }}); App.SomeRoute = BaseRoute.extend(); 
0
source share

All Articles