1

所以我有一堆模板将通过{{#each game}}显示以下模板进行迭代:

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

我想在单击“第 1 页”框时显示“第 2 页”,所以我有以下内容:

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

但我不希望所有其他游戏模板都转换到第 2 页,只希望被点击的那个。我该如何做到这一点?

编辑:更改应该只影响当前用户,而不是所有用户。

4

3 回答 3

1

不要使用会话变量!原因就是您遇到的问题,它们相当于旧的全局变量。改用模板的数据,它是本地的,在这种情况下可以用来控制你想要的行为。

对于您示例中的模板:

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(); 
  },
});
于 2014-04-01T01:54:37.830 回答
1

假设您的游戏存储在Meteor.Collection, 并且condition是文档上的一个属性,应该反映所有用户,而不仅仅是当前用户,您可以执行以下操作:

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

如果它应该只影响当前用户,您可以使用特定于模板实例的会话变量并使用名为的辅助函数返回它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);
};

您可以使用本地集合实现类似的功能。

于 2014-04-01T01:41:03.660 回答
0

我也觉得使用带有 id 的会话听起来不是最好的主意,并发现这个答案似乎比使用会话更好:Using Meteor sessions to toggle templates

于 2015-07-27T05:43:17.687 回答