jnolte jnolte - 2 months ago 5
Javascript Question

Meteor: Hide or remove element? What is the best way

I am quite new with Meteor but have really been enjoying it and this is my first reactive app that I am building.

I would like to know a way that I can remove the

.main
element when the user clicks or maybe a better way would be to remove the existing template (with main content) and then replace with another meteor template? Something like this would be simple and straightforward in html/js app (user clicks-> remove el from dom) but here it is not all that clear.

I am just looking to learn and for some insight on best practice.

//gallery.html
<template name="gallery">
<div class="main">First run info.... Only on first visit should user see this info.</div>
<div id="gallery">
<img src="{{selectedPhoto.url}}">
</div>
</template>

//gallery.js
firstRun = true;

Template.gallery.events({
'click .main' : function(){
$(".main").fadeOut();
firstRun = false;
}
})

if (Meteor.isClient) {

function showSelectedPhoto(photo){
var container = $('#gallery');
container.fadeOut(1000, function(){
Session.set('selectedPhoto', photo);
Template.gallery.rendered = function(){
var $gallery = $(this.lastNode);
if(!firstRun){
$(".main").css({display:"none"});
console.log("not");
}
setTimeout(function(){
$gallery.fadeIn(1000);
}, 1000)
}
});
}

Deps.autorun(function(){
selectedPhoto = Photos.findOne({active : true});
showSelectedPhoto(selectedPhoto);
});

Meteor.setInterval(function(){
selectedPhoto = Session.get('selectedPhoto');

//some selections happen here for getting photos.

Photos.update({_id: selectedPhoto._id}, { $set: { active: false } });
Photos.update({_id: newPhoto._id}, { $set: { active: true } });
}, 10000 );
}

Answer

If you want to hide or show an element conditionaly you should use the reactive behavior of Meteor: Add a condition to your template:

<template name="gallery">
  {{#if isFirstRun}}
  <div class="main">First run info.... Only on first visit should user see  this info.</div>
  {{/if}}
  <div id="gallery">
    <img src="{{selectedPhoto.url}}">
  </div>    
</template>  

then add a helper to your template:

Template.gallery.isFirstRun = function(){
   // because the Session variable will most probably be undefined the first time
   return !Session.get("hasRun");
}

and change the action on click:

Template.gallery.events({
  'click .main' : function(){
    $(".main").fadeOut();
    Session.set("hasRun", true);
  }
})

you still get to fade out the element but then instead of hiding it or removing it and having it come back on the next render you ensure that it will never come back.

the render is triggered by changing the Sessionvariable, which is reactive.

Comments