事件中的流星变化数据上下文变量

时间:2021-10-03 16:25:55

I want to change a variable in the data context in an event. This is what I have tried:

我想在事件中更改数据上下文中的变量。这是我尝试过的:

Template.item.events({
    "click .item": function (event) {
        this.selected = !this.selected;
    }
});

<template name="item">
    <div class="item {{#if selected}}selected{{/if}}">{{text}}  <span class="small">{{message}} - {{createdAt}}</span></div>
</template>

When I'm debugging I get the field selected, together with text and message in the data context. However the view is not updated, why is that?

当我调试时,我会在数据上下文中选择字段和文本和消息。但是视图没有更新,为什么呢?

EDIT:

I can do this Items.update(this._id, {$set: {selected: !this.selected}}); but I actually don't want to put it in the database... Is it not possible to add to the data context?

我可以这样做Items.update(this._id,{$ set:{selected:!this.selected}});但我实际上不想把它放在数据库中...是不是可以添加到数据上下文?

2 个解决方案

#1


I think this is a better approach:

我认为这是一种更好的方法:

$ meteor add reactive-var

Template.item.onCreated(function () {
    this.selectedVar = new ReactiveVar(false);
});

Template.item.events({
    "click .item": function (event, tmpl) {
        tmpl.selectedVar.set(!tmpl.selectedVar.get());
    }
});

Template.item.helpers({
    selected: function () {
        var tmpl = Template.instance();
        return tmpl.selectedVar.get();
    }
});

<template name="item">
    <div class="item {{#if selected}}selected{{/if}}">{{text}}  <span class="small">{{message}} - {{createdAt}}</span></div>
</template>

#2


If you don't want this stored in the database I see no reason to use reactivity or update the data context variables... You could just use basic DOM manipulation like this:

如果您不希望将其存储在数据库中,我认为没有理由使用反应性或更新数据上下文变量......您可以使用这样的基本DOM操作:

Template.item.events({
    "click .item": function (event) {
        $('.item').removeClass('selected');
        $(event.target).closest('.item').addClass('selected');
    }
});

#1


I think this is a better approach:

我认为这是一种更好的方法:

$ meteor add reactive-var

Template.item.onCreated(function () {
    this.selectedVar = new ReactiveVar(false);
});

Template.item.events({
    "click .item": function (event, tmpl) {
        tmpl.selectedVar.set(!tmpl.selectedVar.get());
    }
});

Template.item.helpers({
    selected: function () {
        var tmpl = Template.instance();
        return tmpl.selectedVar.get();
    }
});

<template name="item">
    <div class="item {{#if selected}}selected{{/if}}">{{text}}  <span class="small">{{message}} - {{createdAt}}</span></div>
</template>

#2


If you don't want this stored in the database I see no reason to use reactivity or update the data context variables... You could just use basic DOM manipulation like this:

如果您不希望将其存储在数据库中,我认为没有理由使用反应性或更新数据上下文变量......您可以使用这样的基本DOM操作:

Template.item.events({
    "click .item": function (event) {
        $('.item').removeClass('selected');
        $(event.target).closest('.item').addClass('selected');
    }
});