swennemen
swennemen

Reputation: 955

I misunderstood Session what is a good alternative?

Currently I'm creating an app with meteor en learning it while building. I try to incorporate Sessions instead of writing everything to the database (what I was doing). In my understanding Session is a global object which stores key-value pairs and is reactive. Therefore I thought it would a great choice to use for template rendering specifics in my simple game. My goal is small game, and the different steps will be renderend in a template for each player based on certain action they made.

I rewrote my app and wanted to use Session in this way (simplified of course).

My template:

<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());
    };
})

However this doesn't work they way I thought it would work. It looks like that each Session is individual for each user (what makes sense of course considering it's (sort-of) a replacement of cookies).

So my question is:

Upvotes: 0

Views: 295

Answers (1)

sbking
sbking

Reputation: 7680

Your events and helpers functions are backwards, you're missing a couple curly braces, and your event key (the button's ID) is wrong. Try this:

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

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

Edit: from what you are trying to do, it might make sense to do something like this:

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();
    }
  });
}

Upvotes: 1

Related Questions