2013-03-07 46 views
2

我試圖讓2個小部件出現在ember.js應用程序的多個路徑中。我已經設置了以下作爲演示,http://jsfiddle.net/adice/EyDcy/5/Ember.js - 如何在一個插座中具有多個模型的多個區域

你會看到,我已經找到一種方法通過將以下的路線要做到這一點:

App.IndexRoute = Em.Route.extend({ 
    setupController: function(controller,model) { 
     this._super(controller,model); 
     controller.set('user',App.UsersStore.find(2)); 
     controller.set('site',App.SiteData.find(1)); 
    } 
}); 

但是如果我想有這個可用到每條路線,我真的必須手動將它添加到我製作的所有路線嗎?我試圖將它添加到ApplicationRoute中,但是這會一直返回一個錯誤。

也是一種填充id的方法嗎?我想這樣做

App.appData = Em.Object.create({ 
    currentUserId: 2 
}); 

App.IndexRoute = Em.Route.extend({ 
    setupController: function(controller,model) { 
     this._super(controller,model); 
     controller.set('user',App.UsersStore.find(App.appData.currentUserId)); 
     controller.set('site',App.SiteData.find(1)); 
    } 
}); 

回答

2

既然你要訪問的每個路由的用戶對象,你不必依靠你的路由器上,但​​也許可以把用戶的對象作爲要一個全局變量從您的應用中的任何地方訪問。 有幾個地方可以存儲這些對象。在this updated version of your jsfiddle我已經把它放在ApplicationController中的「當前用戶」屬性:

App.ApplicationController = Ember.Controller.extend({ 
    init: function() { 
    this.set('currentUser', App.UsersStore.find(2)) 
    } 
}); 

使用"needs" syntax你可以從其他控制器訪問其他控制器。見UserDetailsController:

我只是瞭解如何使用
App.UserDetailsController = Ember.ObjectController.extend({ 
    needs: 'application', 
    content: Ember.computed.alias('controllers.application.currentUser') 
}) 

一件事是{{呈現}}幫手:

{{render "user_details"}} 

有了這個,你可以使任意模板( 「user_details」)+控制器(「UserDetailsController」),無論你在哪個路線。 (我認爲這是ember.js人們在談論「單身控制器」時的意思。)

結合所有這一切,我希望你對如何解決問題有更好的想法。