user1506145
user1506145

Reputation: 5286

Meteor change data context variable in event

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?

Upvotes: 0

Views: 514

Answers (2)

Peter Ilfrich
Peter Ilfrich

Reputation: 3816

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:

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

Upvotes: 0

juliancwirko
juliancwirko

Reputation: 1282

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>

Upvotes: 1

Related Questions