2013-05-08 35 views
1

我正在編寫一個混合應用程序,其中包含一些服務器處理和用Ember實現的主UI部分。Ember:共同財產的地方?

所有與認證有關的功能都是基於服務器的,所以當加載頁面時我已經知道(基於cookie)如果用戶被認證或不認證。

總之 - 在客戶端,我有一個userId cookie,如果它被設置,那麼用戶被認證。

現在我需要將這些數據提供給所有模板。

我解決它的應用程序模板(在CoffeeScript中的所有代碼,但沒有什麼特別有語言):

路線

ApplicationRoute = Ember.Route.extend 
    setupController: (controller) -> 
    userId = jQuery.cookie 'userId' 
    if userId == 'undefined' 
     userId = null 
    else 
     userId = parseInt userId, 10 
    controller.set 'userId', userId 

控制器

ApplicationController = Ember.Controller.extend 
    userId: null 

最後,模板

<strong> 
    {{#if userId}} 
    userId: {{userId}} 
    {{else}} 
    No user 
    {{/if}} 
</strong> 

這從應用程序模板起作用,但如果我將它移動到index模板,它總是會顯示'沒有用戶'(我期望控制器有一些原型鏈遍歷)。

我試着移動它boud幫手 - 不工作爲好,助手不會被調用都:

Ember.Handlebars.registerBoundHelper 'userId', -> 
    userId = jQuery.cookie 'userId' 
    if userId == 'undefined' 
    userId = null 
    else 
    userId = parseInt userId, 10 
    userId 
+1

你可能想看看[這個問題](http:// stackoverflow。com/questions/16070390/ember-js-current-user-access-global-variable-from-controller)它有點類似於 – MilkyWayJoe 2013-05-08 13:57:12

+0

類似但不完全。但它看起來像我可以通過將數據附加到全局應用程序對象來解決它。 – Guard 2013-05-08 18:35:37

回答

1

我用App.deferReadiness()App.advanceReadiness()直接上設置全局屬性組合App來處理這種情況。 deferReadiness()保持從初始化ember和advanceReadiness()允許ember完成初始化。

ember api for deferReadiness()

使用此推遲準備,直到某些條件爲真。

例子:

App = Ember.Application.create(); 
    App.deferReadiness(); 

    jQuery.getJSON("/auth-token", function(token) { 
    App.token = token; 
    App.advanceReadiness(); 
    }); 

這使您可以執行異步設置邏輯和推遲啓動 您的應用程序,直到安裝完成。

例如,你可以在App.currentUser使用這個初始化灰燼之前,抓住從cookie中的用戶的ID,並將其存儲:

App = Ember.Application.create({}); 

App.deferReadiness(); 

var userId = "1234";//jQuery.cookie 'userId' 
if (userId == 'undefined') { 
    userId = null; 
    App.set('currentUserLoggedIn', false); 
    //window.location = "/login"; // redirect to login page 
} else { 
    userId = parseInt(userId, 10); 
    App.set('currentUserLoggedIn', true); 
    App.set('currentUser', userId); 
    App.advanceReadiness(); 
} 

可以使用再訪問你的應用程序這在任何地方:

App.get('currentUser'); 

或模板:

{{App.currentUser}} 

JSBin example

+0

實際上我最終只是直接將數據附加到應用程序:App.userId = userId,所以不需要延遲/高級 仍然很好的瞭解這些方法 – Guard 2013-05-08 18:41:25

+0

關於使用延遲/進步的好處是你可以等待ajax或其他異步事情在完成應用程序初始化之前完成。我專門用它來查詢api端點,以獲取當前登錄用戶的用戶對象,並在初始化應用程序之前手動將其加載到商店中。 – CraigTeegarden 2013-05-08 18:43:32

+0

是的,我從你的例子中瞭解它 – Guard 2013-05-08 18:49:57