我创建了一个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.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);
},
});
答案 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);