我有带嵌套动态段的路由,例如/:locale / products /:product_id / items /:item_id等嵌套.我想在区域设置路由中的操作中替换区域设置.我更改语言环境时,我不想转换到base /:locale路由.
区域路线行动:
actions: { localeChanged: function(locale) { var route = this.controllerFor('application').get('currentRouteName'); this.transitionTo(route,locale); } }
这只适用于我没有深度嵌套的情况.我想避免在每个路由中实现localeChanged操作,以提供给定路由所需的确切模型.
更新1 – 脏解决方案:
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); } }
我说脏,因为迭代this.router.router.currentHandlerInfos似乎容易出错.有没有更好的办法?
解决方法
您可以创建一个添加此操作的baseRoute.然后您的所有路线都可以从此基本路线继承.您只需编写一次代码,并在所有路径中共享.例如.
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();