【问题标题】:I misunderstood Session what is a good alternative?我误解了 Session 有什么好的选择?
【发布时间】:2014-08-06 02:01:49
【问题描述】:

目前我正在使用流星创建一个应用程序,并在构建时学习它。我尝试合并 Sessions 而不是将所有内容都写入数据库(我在做什么)。在我的理解中,Session 是一个全局对象,它存储键值对并且是反应式的。因此,我认为在我的简单游戏中使用模板渲染细节是一个不错的选择。我的目标是小游戏,不同的步骤将根据每个玩家所做的特定动作在模板中呈现。

我重写了我的应用程序并希望以这种方式使用 Session(当然是简化了)。

我的模板:

<template name="gameRoom">

  <button id='click'>click</button>

  {{#if lastAction}}
    {{>waiting}}
  {{/if}}
</template>



Template.gameRoom.events({
      lastAction: function() {
       return Session.get('lastAction') === Meteor.userId();
    };   
})

Template.gameRoom.helpers({
      'click #click' : function() {
        Session.set('lastAction', Meteor.userId());
    };
})

但是,按照我认为可行的方式,这不起作用。看起来每个 Session 对于每个用户来说都是单独的(考虑到它(某种)是 cookie 的替代品,这当然是有道理的)。

所以我的问题是:

  • Sessions 有没有好的替代方案?我真的需要一个 替代方案还是为此使用数据库可以?本地数据库呢?

【问题讨论】:

    标签: meteor


    【解决方案1】:

    您的 events 和 helpers 函数是倒退的,您缺少一对花括号,并且您的事件键(按钮的 ID)是错误的。试试这个:

    Template.gameRoom.helpers({
      lastAction: function() {
        return Session.equals('lastAction', Meteor.userId());
      }
    });
    
    Template.gameRoom.events({
      'click #click': function() {
        Session.set('lastAction', Meteor.userId());
      }
    });
    

    编辑:从你想要做的事情来看,做这样的事情可能是有意义的:

    Actions = new Meteor.Collection('actions');
    
    if (Meteor.isClient) {
      Template.gameRoom.events({
        'click #click': function() {
          Actions.insert({userId: Meteor.userId()});
        }
      });
    
      Template.gameRoom.helpers({
        lastAction: function() {
          var lastAction = Actions.findOne() || {};
          return lastAction.userId === Meteor.userId();
        }
      });
    }
    

    【讨论】:

    • 谢谢我还不知道 Session.equals :)。但是,也许我误解了你的评论。但我的目标是:如果一个用户点击按钮,模板只显示给该用户。但我认为 Session 不是正确的工具,因此我问什么是最好的选择。
    • 您可以为此使用数据库。请参阅我的编辑。请注意,您仍然需要为 insert 添加允许规则,以防止用户连续执行 2 项操作。
    • 谢谢。为此使用数据库感觉有点脏。感谢您解决这个问题:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-08
    • 1970-01-01
    • 2012-05-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多