2013-05-08 37 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