2013-02-26 56 views
14

我有一個路由器設置帳戶和帳戶/:account_id選項。當用戶登錄到我的應用程序的索引頁面時,我將它們轉換爲帳戶路線。Ember.js:transitionTo路由,然後到動態段

Social.Router.map(function() { 
    this.resource('accounts', function(){ 
     this.resource('account', { path: ':account_id'}); 
    }); 
}); 

Social.IndexRoute = Ember.Route.extend({ 
    redirect: function() { 
     this.transitionTo('accounts'); 
    } 
}); 

我想要做的就是根據一些標準將它們轉換到指定的:account_id路由。目前我只想獲得陣列中的第一個帳戶並使用它。但是將來它可能是一種將他們轉換到他們正在查看的最後一個帳戶的方式。事情是這樣的:

Social.IndexRoute = Ember.Route.extend({ 
    redirect: function() { 
     this.transitionTo('accounts/:account_id'); 
    } 
}); 

的文檔給 「細節」,但沒有提供一個例子,僅提供了以下內容:

transitionTo (name, models)

Transition into another route. Optionally supply a model for the route in question. The model will be serialized into the URL using the serialize hook.

我已經試過如下:

this.transitionTo('accounts/4'); 
Uncaught Error: assertion failed: The route accounts/4 was not found 

this.transitionTo('accounts', Social.Account.find(1)); 
Uncaught More objects were passed than dynamic segments 

回答

13

我放在一起別人的答案和一些擺弄和這個答案出來了:

這樣定義你的路由:

this.resource('accounts', function() { 
    this.route('account', {path: '/:account_id'}); 
}); 

重定向:

this.transitionTo('accounts.account', accountObj); 

但如果從服務器加載,則需要加載accountObj對象b安伏重定向:

var accountObj = App.Account.find(1); 
accountObj.one('didLoad', this, function() { 
    this.transitionTo('accounts.account', accountObj); 
}); 

我成立了this fiddle與完整的例子

+0

你的小提琴似乎沒有工作,所以我用來自CDNjs.com的電話進行了更新:http://jsfiddle.net/XNyme/9/ – commadelimited 2013-02-28 21:31:20

2

它看起來像transitionTo不贊成使用transitionToRoute。

儘管如此,您可以通過使原始聲明爲this.resource('account', { path: '/:account_id'});,然後使用單個創建的對象進行轉換來實現重新路由。

2

您沒有正確指定路徑路徑,您應該有資源下的路線,而不是另一個資源。它應該是這樣的:

Social.Router.map(function() { 
    this.resource('accounts', function(){ 
     this.route('account', { path: '/:account_id'}); 
    }); 
}); 

Social.IndexRoute = Ember.Route.extend({ 
    redirect: function() { 
     this.transitionTo('accounts.account', Social.Account.find(1)); 
    } 
}); 
+0

好。實現這個代碼讓我有兩件事。 1)URL按預期變化。 2)我得到一個控制檯錯誤'未捕獲的錯誤:斷言失敗:沒有找到路由帳戶。 當我登錄'/'時,URL變爲'/#/ accounts/1',這是我所期望的,但沒有加載,並且出現控制檯錯誤。 – commadelimited 2013-02-27 21:37:23

+0

我忘了將路徑添加到根帳戶資源。 – buuda 2013-02-28 15:08:26

0

由於您的/:account_id是您需要transitionToRoute'帳戶'的資源。您也需要相應的AccountRoute。

如果/:account_id是一個路徑而不是資源,你會transitionToRoute'accounts.account',你的路由處理器將被稱爲AccountsAccountRoute。

1

隨着最新的灰燼(1.0.0-RC-6),這完美的作品。

路由器:

this.resource('accounts', function() { 
    this.resource('account', {path: '/:account_id'}); 
}); 

重定向:

this.transitionToRoute('account', Social.Account.find(1)) 
+0

它只適用於燼1.1.3 + pre.e0ffbf84。謝謝。 – hiroshi 2013-11-20 13:30:15