I have a ‘posts’ template that gets displayed multiple times with an #each loop. In these templates’ onCreated() function, I want to access the meteor Template.instance() to use with jQuery to change some UI stuff. The problem is, this works perfectly for the first instance of the template ie.the one I display on top, but for the others, Template.instance() returns null and nothing works. I have tried every variation of this and I can’t seem to find an answer anywhere.
Here’s the code that doesn’t work:
Template.Challenge_Box.onCreated(function(){
var self = this;
self.subscribe('likes.document',self.data._id,function(){
console.log(self);
let likeState = Likes.find({},{user:{$eq:Meteor.userId()}}).count()>0?true:false;
console.log(likeState);
toggleLikeButton(likeState,self.$('#like-button'));
});
});
And here’s the rest of the code:
Template.Challenge_Box.events({
'click #like-button':function(event){
//console.log($(event.target));
if($(event.target).hasClass('liked')){
//console.log('toggle: false');
toggleLikeButton(false,event.currentTarget);
}else{
//console.log('toggle: true');
toggleLikeButton(true,event.currentTarget);
}
console.log(Template.instance().data._id);
Meteor.call('likes.toggle',Template.instance().data._id);
}
});
function toggleLikeButton(toggle,target) {
if(toggle){
console.log('button-toggle: true, ',target);
$(target).removeClass('btn-outline-danger');
$(target).addClass('btn-danger');
$(target).addClass('liked');
}else{
console.log('button-toggle: false, ',target);
$(target).removeClass('btn-danger');
$(target).addClass('btn-outline-danger');
$(target).removeClass('liked');
}
}