Meteor.js: 从 RouteController waitOn 访问 Session 变量
Meteor.js: access Session variable from RouteController waitOn
我需要在我的流星应用程序的 waitOn
函数中从 RouteController 访问一个会话变量,我在模板的 onCreated
块上设置了一个会话变量:
Template.practicalQuestionForm.onCreated ->
Session.set 'domId', Random.id()
然后我需要从我的控制器访问那个 Session 变量 Session.get 'domId'
,查看 waitOn
:
@testsAddQuestionController = testsQuestionsController.extend
template: ->
qType = Router.current().params.type
if qType == 'practical'
'practicalQuestionForm'
else if qType == 'mcq'
'mcqQuestionForm'
waitOn: ->
console.log Session.get 'domId'
Meteor.subscribe 'currentSessionUploads', Session.get 'domId'
data: ->
questions: TestQuestions.find()
test: Tests.findOne slug: this.params.slug
previous: TestQuestions.find({}, sort: createdAt: 1, limit: 1).fetch().pop()
但是我只得到 undefined
谁能告诉我这是否可行?如果不能,您还有什么其他选择可以建议我?
提前致谢。
如果您想在 waitOn
函数中使用 Session
,您需要确保此代码将在客户端上执行。
例如:
waitOn: function() {
var domId = undefined;
if(Meteor.isClient) {
domId = Session.get('domId');
}
return Meteor.subscribe('currentSessionUploads', domId);
}
请注意,您需要检查 domId
在您的发布(服务器端)中是否未定义。
此外,您必须检查您的 Session
变量是否尚未定义,否则您将陷入无限循环并且您的控制器会变得疯狂:
Template.practicalQuestionForm.onCreated ->
if not Session.get 'domId'
Session.set 'domId', Random.id()
我需要在我的流星应用程序的 waitOn
函数中从 RouteController 访问一个会话变量,我在模板的 onCreated
块上设置了一个会话变量:
Template.practicalQuestionForm.onCreated ->
Session.set 'domId', Random.id()
然后我需要从我的控制器访问那个 Session 变量 Session.get 'domId'
,查看 waitOn
:
@testsAddQuestionController = testsQuestionsController.extend
template: ->
qType = Router.current().params.type
if qType == 'practical'
'practicalQuestionForm'
else if qType == 'mcq'
'mcqQuestionForm'
waitOn: ->
console.log Session.get 'domId'
Meteor.subscribe 'currentSessionUploads', Session.get 'domId'
data: ->
questions: TestQuestions.find()
test: Tests.findOne slug: this.params.slug
previous: TestQuestions.find({}, sort: createdAt: 1, limit: 1).fetch().pop()
但是我只得到 undefined
谁能告诉我这是否可行?如果不能,您还有什么其他选择可以建议我?
提前致谢。
如果您想在 waitOn
函数中使用 Session
,您需要确保此代码将在客户端上执行。
例如:
waitOn: function() {
var domId = undefined;
if(Meteor.isClient) {
domId = Session.get('domId');
}
return Meteor.subscribe('currentSessionUploads', domId);
}
请注意,您需要检查 domId
在您的发布(服务器端)中是否未定义。
此外,您必须检查您的 Session
变量是否尚未定义,否则您将陷入无限循环并且您的控制器会变得疯狂:
Template.practicalQuestionForm.onCreated ->
if not Session.get 'domId'
Session.set 'domId', Random.id()