【问题标题】:Where should Session values be initiated in a Meteor app?在 Meteor 应用程序中应该在哪里启动会话值?
【发布时间】:2015-09-08 02:46:36
【问题描述】:

根据 Dan Dascalescu 的回答 here,我想在 Meteor 中实现这样的动态模板:

在 main.html 中:

<body TEXT="#000000">

<div class="container">
    {{> mnuScheduler}}
    {{> Template.dynamic template=currentTemplate}}
</div>

</body>

在 main.js 中:

Template.body.helpers({
  currentTemplate: function () {
    return Session.get('curTemplate');
  }
});

但显然我需要将我的会话变量 'curTemplate' 启动到我要显示的第一个模板,例如:

Session.setDefault('curTemplate', 'tblScheduler');

...然后像这样在其他地方动态设置它:

Session.set('curTemplate', somethingElseBasedOnContext);

我的问题是,初始 (setDefault) 属于哪里?应该是我的 main.js 以及 Template.body.helpers(我也有 Meteor.subscribe("bla") 调用吗?

【问题讨论】:

    标签: javascript meteor session-variables single-page-application meteor-blaze


    【解决方案1】:

    以下三个位置中的任何一个都可以使用:

    if (Meteor.isClient) {
      Session.set('curTemplate', 'tblScheduler');         // <---  
      console.log('Meteor.isClient');
    
      Meteor.startup(function() {
        //Session.set('curTemplate', 'tblScheduler')      // <---
        console.log('Meteor.startup');
      });
    
      Template.body.onCreated(function() {
        //Session.set('curTemplate', 'tblScheduler')      // <---
        console.log('Template.body.onCreated');
      });
    
      Template.body.helpers({
        currentTemplate: function() {
          return Session.get('curTemplate');
        },
      });
    }
    

    使用此代码,浏览器日志会显示启动时调用它们的顺序:

    Meteor.isClient
    Template.body.onCreated
    Meteor.startup
    

    Meteor.startup 在 DOM 准备好之前不会运行,但是在这种情况下这不是一个因素。

    Meteor 在构建应用程序方面非常灵活,因此最好在您的方法中保持一致。

    在这里,您可以决定将启动代码放在 Meteor.startup 块中,或者您可以决定因为需要渲染主体模板,所以 Template.body.onCreated 是它的正确位置。但尽量保持一致!

    【讨论】:

    • Meteor.startup() 可能也是调用 Meteor.subscribe("bla") 的首选位置,对吧?
    • 对于您希望始终处于活动状态的订阅,这是放置 Meteor.subscribe 调用的好地方。
    • 对于您希望始终处于活动状态的订阅,这是放置 Meteor.subscribe 调用的好地方。但是,在某些时候,您会想要考虑使用特定于模板的订阅(在 onRendered 回调中订阅)或为此使用 iron:router(或类似的)。然而,仅仅在 if( Meteor.isClient ) {} 块中(或在 /client 目录中)也可以工作,因为所有代码都是在客户端启动时执行的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-27
    • 1970-01-01
    • 2013-07-19
    • 1970-01-01
    • 2021-12-26
    • 2012-02-11
    相关资源
    最近更新 更多