سؤال

So I have a bunch of templates that will be iterated with {{#each game}} showing the following template:

<template name="game">
{{#if condition}}
    <div class="box">
        Page 1
    </div>
{{else}}
    <div class="box">
        Page 2
    </div>
{{/if}}
</template>

I want to display "Page 2" when the "Page 1" box is clicked, so I have the following:

Template.game.events({
    'click .box': function(e) {
        Session.set("condition", true);
    }
});

But I do not want all of the other game templates to transition to Page 2, just the one that was clicked. How do I accomplish this?

EDIT: The change should only affect the current user, not all users.

هل كانت مفيدة؟

المحلول

Assuming your games are stored in a Meteor.Collection, and condition is a property on the documents that should reflect for all users, not just the current one, you can do something like this:

Template.game.events({
    'click .box': function(event, template) {
        Games.update(
            {_id: template.data._id},
            {$set: {condition: !template.data.condition}}
        );
    }
});

If it should only affect the current user, you can use a template-instance specific session variable and return it with a helper function called condition:

Template.game.events({
    'click .box': function(event, template) {
        Session.set("condition-" + template.data._id, true);
    }
});

Template.game.condition = function() {
    return Session.get("condition-" + this._id);
};

You could achieve similar functionality with a local collection.

نصائح أخرى

Don't use Session variables! The very reason is the problem you have, they're equivalent of the old global variables. Use template's data instead, it's local and can be used to control the behavior like you want in this case.

For the template in your example:

Template.game.created = function() {
  this.data.conditionValue = 'something';
  this.data.conditionDep = new Deps.Dependency();
};

Template.game.condition = function() {
  this.conditionDep.depend();
  return this.conditionValue;
};

Template.game.events({
  'click .box': function(e, t) {
    t.data.conditionValue = 'somethingElse';
    t.data.conditionDep.changed(); 
  },
});

I also feel using a session with id doesn't sound like the best idea, and found this answer which seems to be better than using session: Using Meteor sessions to toggle templates

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top