2013-03-07 47 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人们在谈论“单身控制器”时的意思。)

结合所有这一切,我希望你对如何解决问题有更好的想法。