Meteor.js:从RouteController waitOn访问Session变量

时间:2015-08-02 07:47:49

标签: session meteor coffeescript iron-router

我需要从我的meteor应用程序中的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有人可以告诉我这是否可能?如果没有,你可以告诉我什么其他选择?

提前致谢。

1 个答案:

答案 0 :(得分:2)

如果您想在Session函数中使用waitOn,则需要确保此代码将在客户端上执行。

例如:

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()
相关问题