簡體   English   中英

ember.js - 從任何路由交換嵌套資源

[英]ember.js - swap out a nested resource from any route

我有帶嵌套動態段的路由,例如/: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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM