Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Meteor sessions to toggle templates

I'm brand new to JavaScript and Meteor, and am a little stuck in trying to create edit functionality for a list item to be able to modify properties of the list item (from a Mongo document). I can make it work if I make editMode a boolean property of the item itself, but I'd like it to be local and temporary rather than stored with the document itself.

Looking at the code below, you'll notice I'm still green and don't yet completely understand what I'm doing, but you should be able to understand what I'm trying to do :)

The code is somewhat there, but am trying to hook up changes in the session, based on toggling an edit button, to get the edit mode template to render. Here's what I have (stripped down to the relevant stuff):

// Item template

<template name="item">
  <div class="item">
    <span>{{itemText}}</span>
    <span class="glyphicon glyphicon-pencil item-edit" aria-hidden="true"></span>
  </div>
  <div class="mod-table">
    {{#if this.editMode}}
      {{> modTable}}
    {{/if}}
  </div>
</template>

// Associated .js file

Session.set(this.editMode, false);

Template.item.events({
  'click .item-edit': function() {
    if (this.editMode) {
      Session.set(this.editMode, false);
    } else {
      Session.set(this.editMode, true);
    }
  }
});
like image 890
Erik Johnson Avatar asked Feb 20 '26 00:02

Erik Johnson


1 Answers

Don't use Session variables because they are global thus considered bad practice, you should use a ReactiveVar tied to your item template instead.

item.html :

<template name="item">
  <div class="item">
    <span>{{itemText}}</span>
    <span class="glyphicon glyphicon-pencil item-edit" aria-hidden="true"></span>
  </div>
  <div class="mod-table">
    {{#if editMode}}
      {{> modTable}}
    {{/if}}
  </div>
</template>

item.js :

Template.item.created=function(){
  this.editMode=new ReactiveVar(false);
};

Template.item.helpers({
  editMode:function(){
    return Template.instance().editMode.get();
  }
});

Template.item.events({
  'click .item-edit': function(event,template) {
    var editMode=template.editMode.get();
    template.editMode.set(!editMode);
  }
});

Don't forget to meteor add reactive-var to your project !

like image 108
saimeunt Avatar answered Feb 22 '26 14:02

saimeunt