Javascript 灰烬:一个共有财产的地方?

Javascript 灰烬:一个共有财产的地方?,javascript,ember.js,Javascript,Ember.js,我正在编写一个混合应用程序,其中包含一点服务器处理和使用Ember实现的主要UI部分 所有与身份验证相关的功能都是基于服务器的,因此当页面加载时,我已经知道(基于cookies)用户是否经过身份验证 简言之,在客户端,我有一个userIdcookie,如果设置了它,那么用户就被验证了 现在,我需要将这些数据提供给所有模板 我为应用程序模板解决了这个问题(所有代码都是CoffeeScript,但语言没有什么特别之处): 路线 控制器 ApplicationController = Ember.Co

我正在编写一个混合应用程序,其中包含一点服务器处理和使用Ember实现的主要UI部分

所有与身份验证相关的功能都是基于服务器的,因此当页面加载时,我已经知道(基于cookies)用户是否经过身份验证

简言之,在客户端,我有一个
userId
cookie,如果设置了它,那么用户就被验证了

现在,我需要将这些数据提供给所有模板

我为应用程序模板解决了这个问题(所有代码都是CoffeeScript,但语言没有什么特别之处):

路线

控制器

ApplicationController = Ember.Controller.extend
  userId: null
最后是模板

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

我使用了
App.deferReadiness()
App.advanceReadiness()
以及直接在
App
上设置全局属性来处理这种情况
deferReadiness()
阻止ember初始化,而
advanceReadiness()
让ember完成初始化

从:

使用此选项延迟准备就绪,直到某个条件为真

例如:

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

   jQuery.getJSON("/auth-token", function(token) {
     App.token = token;
     App.advanceReadiness();
   });
这允许您执行异步设置逻辑和延迟引导 在安装完成之前,请关闭应用程序

例如,在初始化ember之前,您可以使用它从cookie中获取用户id,并将其存储在
App.currentUser

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}}

我使用了
App.deferReadiness()
App.advanceReadiness()
以及直接在
App
上设置全局属性来处理这种情况
deferReadiness()
阻止ember初始化,而
advanceReadiness()
让ember完成初始化

从:

使用此选项延迟准备就绪,直到某个条件为真

例如:

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

   jQuery.getJSON("/auth-token", function(token) {
     App.token = token;
     App.advanceReadiness();
   });
这允许您执行异步设置逻辑和延迟引导 在安装完成之前,请关闭应用程序

例如,在初始化ember之前,您可以使用它从cookie中获取用户id,并将其存储在
App.currentUser

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}}

你可能想看看哪一个有点相似,但不完全相同。但看起来我可以通过将数据附加到全局应用程序对象来解决这个问题。你可能想看看哪一个有点类似,但不完全相同。但看起来我可以通过将数据附加到全局应用程序对象来解决这个问题。实际上,我只是直接将数据附加到应用程序:App.userId=userId,因此,不需要延迟/提前,了解这些方法仍然很好使用延迟/提前的好处是,在完成应用程序初始化之前,您可以等待ajax或其他异步操作完成。我专门使用它来查询api端点,以获取当前登录用户的用户对象,并在初始化应用程序之前手动将其加载到存储中。实际上,我只是直接将数据附加到应用程序:app.userId=userId,因此,不需要延迟/提前,了解这些方法仍然很好使用延迟/提前的好处是,在完成应用程序初始化之前,您可以等待ajax或其他异步操作完成。我专门使用它来查询api端点,以获取当前登录用户的用户对象,并在初始化应用程序之前手动将其加载到应用商店中。