Ember.js:无法访问注入的对象

时间:2014-10-28 01:09:18

标签: ember.js

我创建了一个Session对象:

App.Session = Ember.Object.extend({
  user: null,
  userID: '',
});

我注入了这个对象:

Ember.Application.initializer({
name: 'login',
initialize: function (container, application) {
  App.register('session:main', App.Session, { instantiate: false, singleton: true }); 
  // Add `session` object to route to check user
  App.inject('route', 'session', 'session:main');
  // Add `session` object to controller to visualize in templates
  App.inject('controller', 'session', 'session:main');

  App.register('firebase:main', App.Firebase);
  // Add `session` object to route to check user
  App.inject('route', 'firebase', 'firebase:main');
  // Add `session` object to controller to visualize in templates
  App.inject('controller', 'firebase', 'firebase:main');
  }
});

我想将userID Session属性设置为当前用户的ID,如下所示:

Ember.Route.reopen({
  beforeModel: function (transition) {
    var isAuth = false;
    var user = '';
    var store = this.store;
    var _this = this;
    var firebase = new Firebase("https://dynamicslife.firebaseio.com");
    firebase.onAuth(function(authData) {
      if (authData) {
        isAuth = true;
        _this.session.userID = authData.id; //THIS OPERATIONS IS NOT WORKING!!!!!!
      } else {
        isAuth = false;
      }
    });

    // These routes you do not need to be logged in to access.
    var openRoutes = ['home','index','about','stories'];
    var testMode = false;
    if (testMode == false) {
    if (openRoutes.indexOf(transition.targetName) === -1 && isAuth === false) {
      console.log('Please login to access this information');
      this.transitionTo('stories');
    }  
  }
 }
});

在上面标识的代码表达式中://THIS OPERATIONS IS NOT WORKING!!!!!!authData.id包含正确的ID值。但是_this.session.userID仍未定义。

我尝试将_this.session.userID = authData.id;替换为_this.session.set('userID', authData.id);,但这给了我同样的错误。

我认为可能会将Session对象注入Ember.Route.reopen。如果是这种情况,我如何从Ember.Route.reopen

访问Session对象

由于session.userID未定义,我收到以下错误:

Error while processing route: statistics.index session is not defined ReferenceError: session is not defined

当Ember运行时:

App.StatisticsRoute = Ember.Route.extend({
  model: function() {
    return this.store.find('user', session.userID);
  },
});  

1 个答案:

答案 0 :(得分:2)

您告诉它不要实例化App.Session,这意味着它是您要使用的对象,但它是class而不是instance }

App.register('session:main', App.Session.create(), { instantiate: false, singleton: true }); 
路由中session上存在

this,而不是全局命名空间。

App.StatisticsRoute = Ember.Route.extend({
  model: function() {
    return this.store.find('user', this.session.get('userID'));
  },
});  

你绝对应该使用setter

 _this.session.set('userID', authData.id);