in Meteor, how do i update a property on only one instance of a template? - meteor

If I have an {{# each}} binding in Meteor, and I want to update a property on only one instance of the template inside the #each. How would I do that? I've tried setting a value on the "template" object inside the events map, but that doesn't seem to be reactive. I've also tried binding to a Session property, but that will cause every instance to update instead of just the one I want...
for example:
{{#each dates}}
{{> dateTemplate}}
{{/each}}
<template name="dateTemplate">
{{date}}
<span style="color: red;">{{errorMsg}}</span> <--- how do i update errorMsg?
</template>
Template.dateTemplate.events({
'click': function(event, template) {
template.errorMsg = 'not valid'; <--- this doesn't do anything
}
});
EDIT TO ADDRESS ANSWER BELOW:
Template.dateTemplate.events({
'click': function(event, template) {
template.errorMsg = function() { return 'not valid';} <--- this also doesn't do anything
}
});

You don't have to use handlebars for this, because its not something that needs reactivity to pass the message through, reactive variables work best with db data, or data that would be updated by another client over the air.
You could use JQuery (included by default) to update it, it can also get a bit fancier:
<template name="dateTemplate">
{{date}}
<span style="color: red;display: none" class="errorMessage"></span>
</template>
Template.dateTemplate.events({
'click': function(event, template) {
$(template.find('.errorMessage')).html('Your Error Message').slideDown();
}
});
Ive edited it so the error is hidden by default, and slides down with an animation

I'm experimenting handling this by passing a different reactive object to each instance of the template. Then the template can bind to the reactive object (which is unique per instance) and we don't have any extra boilerplate.
It ends up looking like this:
Initial render:
Template.firstTemplateWithPoll(ContextProvider.getContext())
Template.secondTemplateWithPoll(ContextProvider.getContext())
// (I actually pass getContext an identifier so I always get the same context for the same template)
JS:
Template.poll.events = {
'click .yes' : function() {
this.reactive.set('selection', 'yes');
},
'click .no' : function() {
this.reactive.set('selection', 'no');
}
};
Template.poll.selection = function(arg) {
return this.reactive.get('selection');
}
Template:
<template name="poll">
<blockquote>
<p>
Your selection on this poll is {{selection}}
</p>
</blockquote>
<button class='yes'>YES</button>
<button class='no'>NO</button>
</template>

template.errorMsg should be a function that returns your error.
Template.dateTemplate.events({
'click': function(event, template) {
template.errorMsg = function() { return 'not valid'; };
}
});

Related

Document element null in template due to helper condition

This Meteor client code is expected to show a progress bar animation when a button is clicked. The problem is that the progress element is null when the animation code tries to use it.
How can it be fixed? thx
Template.registerHelper('session', (value) => {
return Session.get(value);
})
Template.footer.events({
'click button[data-action=carSearch]': function (e) {
e.preventDefault();
clickInfo();
}
});
'clickInfo': function () {
Session.set('inProgress', true); // makes the element visiable
progressBarStart(); // start the animation
}
'progressBarStart': function () {
let bar = document.getElementById('bar'); //<-- bar is always null
if (bar.value < 70) {
setTimeout(lib.progressBarStart(), 1000); controls the speed
bar.value += 1;
}
}
<template name="nameSearch">
<div id="nameSearch">
<p id="result" data-id={{_id}}>
{{{display.result}}} <br>
{{#if (session 'inProgress')}}
<progress id="bar" value="0" max="70"></progress>
{{/if}}
</p>
</div>
</template>
You should give the render a time to re-render after calling Session.set('inProgress', true);, 50ms will be enough.
Next, you should declare clickInfo and progressBarStart correctly, not like you have them now.
function clickInfo() {
Session.set('inProgress', true);
Meteor.setTimeout(progressBarStart, 50);
}
function progressBarStart() {
...
}
I'd also recommend to use dedicated helper to obtain inProgress status:
Template.footer.helpers({
isInProgress: function() {
return Session.equal('inProgress', true);
}
});
And use it in your template:
{{#if isInProgress}
...
{{/if}}
You must not use Session variables for such a small reason. Meteor JS has given a facility to use Reactive Variables at template level manipulations.
You should give the render a time to re-render after calling Template.instance().inProgress.set(true);.
I'd also recommend to use dedicated helper to obtain inProgress status:
Template.footer.onCreated(function(){
this.inProgress = new ReactiveVar(false);
});
Template.footer.helpers({
isInProgress: function() {
return Template.instance().inProgress.get();
}
});
And use it in your template:
{{#if isInProgress}
...
{{/if}}

meteor simple reactive var

I'm working in meteor trying to use a reactive var to switch the content in the main panel between two tabs. I've been able to test the content successfully on it's own so I'm fairly confident the issue lies in the reactive var code. Specifically I think the issue is with the tab: function() but after many searches and reading documentation I haven't found a solution.
The relevant js:
Template.content.onCreated( function() {
this.currentTab = new ReactiveVar('form');
});
Template.content.helpers({
tab: function() {
return Template.instance().currentTab.get();
}
});
Template.content.events({
'click .nav li': function (event, template) {
var currentTab = $( event.target ).closest( "li" );
currentTab.addClass( "active" );
$( ".nav li" ).not( currentTab ).removeClass( "active" );
Template.currentTab.set();
}
});
The relevant html:
<template name ="content">
<ul class ="nav">
<li data-template="form">Form</li>
<li data-template="results">Results</li>
</ul>
{{ > Template.dynamic template=tab}}
</template>
{{ > Template.dynamic template=tab}}
This is calling the tab helper to get a string that is the name of the template you want to show here. It should work the first time because you start out by setting the value of currentTab to "form".
To change the template that gets shown, you need to change the value of currentTab to a string matching the name of the new template. You're not doing that.
Template.currentTab.set();
This is where you should be doing that. Instead you're calling set() on the currentTab property of Template, which I don't think exists. Template with a capital T is a Meteor object, not the template instance that I think you're trying to refer to. And to set a new value for currentTab, you actually need to provide a value. Like so:
Template.content.events( {
'click .nav li': function(event, instance) {
//logic to decide which template you want to show
//and put the name of that template in templateName
instance.currentTab.set(templateName)
}
});

Meteor with ViewModel package not updating accross multiple child templates

I am new to meteor, and have a basic understanding of what is going on, but I am stuck with this example (the problem has been simplified as much as possible):
I have a template, and a child template:
<template name="test">
{{#each items}}
{{> testItem}}
{{/each}}
{{#each items}}
{{> testItem}}
{{/each}}
</template>
<template name="testItem">
<div {{ b "click: toggle"}}>{{value}}</div>
</template>
Template.test.viewmodel({
items: [],
onCreated: function() {
this.items().push({ value: 'test' });
}
})
Template.testItem.viewmodel({
toggle: function() {
this.value("changed");
}
});
The thing here is we have a single array of items in the viewmodel, and we render it through a child template multiple times.
When we toggle the item, it only toggles the single item template, not the other representation of it. It is behaving like it is copying the value, or some sort of scoping is taking place.
My expectation would be the second item to also change, but this is not the case - what am I missing, or misunderstanding here?
EDIT - Additional Investigation
If I change the item through the parent, and notify it has changed, the changes propogate throughout the child templates
Template.testItem.viewmodel({
toggle: function () {
this.parent().items()[0].value = "changed";
this.parent().items().changed();
}
});
Thanks!
You're right, when you do this.value("changed"); you're changing the value of the testItem view model, not the parent array. If you're going to modify the properties of objects in an array I highly recommend you use a client side Mongo collection instead. It will save you a lot of headaches.
Items = new Mongo.Collection(null);
Template.test.viewmodel({
items: function() {
return Items.find();
},
onCreated: function() {
Items.insert({ _id: "1", value: 'test' });
}
})
Template.testItem.viewmodel({
toggle: function() {
Items.update({ _id: this._id() }, { value: 'changed' });
}
});
btw, I rarely check SO. You will get quicker responses on viewmodelboard.meteor.com

Meteor data context to child template

I have a route and a template, that has the right data context as defined in the routes.js:
this.route('entrant_view_race', {
path: '/organise/entrants/:_id/',
yieldTemplates: navOrganise,
waitOn: function() {
return Meteor.subscribe('entrants');
},
data: function() {
return Races.findOne(this.params._id);
}
});
The data context is set to the data function above no problems. Within entrant_view_race template/route we have another template:
<div class="row">
<div class="col-md-4">
{{> chart_entrant_status}}
</div>
</div>
Now within chart_entrant_status is a subscription which passes a param which is defined in the data context:
Meteor.subscribe('entrantStatusCount', this._id);
but this._id is undefined. I believed that whatever the data context of the parent is passed to child templates unless you explicitly define such as {{> chart_entrant_status dataContext}} ? How do I pass the _id of the parent context to the child template (I don't want to use session variables).
EDIT:
chart_entrant_status template looks like this:
<template name="chart_entrant_status">
{{#chart_container title="Entrants" subtitle="Status" class="race-status"}}
{{_id}}
<div id="chart"></div>
{{> table_entrant_status}}
{{/chart_container}}
</template>
Note {{_id}} is rendered fine so the context is alive to that point. And the subscription when the template is rendered:
Template.chart_entrant_status.rendered = function() {
Meteor.subscribe('entrantStatusCount', this._id); // this._id is undefined - if I substitute for the actual id as a string Ba48j2tkWdP9CtBXL I succeed....
}
But no cigar... struggling to find where I lose the data context...
EDIT2: This returns this._id fine...
Template.chart_entrant_status.helpers({
stuff: function() {
return this._id; // returns the right id in {{stuff}} in the template
}
})
So is the data context not available to Template.chart_entrant_status.rendered?
EDIT4: solved. It's this.data._id.... ahhhh
this.data._id was the correct answer

In iron router, how to avoid recompute the entire data field when only a subset is changed

In Iron-router, we can pass the data to a page in the data field. For example:
Router.map(function () {
this.route('myroute', {
path: '/route',
template: 'myTemplate',
data: function () {
return {
title: getTitle(),
description: getDescription(),
}
}
});
});
In the template, title and description are actually some value passed to subtemplates:
<template name="myTemplate">
{{> titleTemplate title}}
{{> descriptionTemplate description}}
</template>
Since the data field in the iron-router is reactive, whenever a session variable change, the data field is recalculated.
In this case, however, the session variable in getTitle function only changes the template "titleTemplate", and the session variable in getDescription() function only changes the template "descriptionTemplate".
If the session variable in the getTitle() function changes, I would like to only execute the getTitle() function, and do not execute the getDescription() function. If possible, I would also like to only render the "titleTemplate" and do not render "descriptionTemplate".
I wonder whether that is possible. If this is not the right way of writing the Meteor application, what is a better way to do it?
Thanks.
This is an interesting situation. Despite the fact that the getTitle and getDescription functions may be dependent on completely different reactive variables, they will both be recomputed whenever either one of them changes.
One possible solution is to pass the functions themselves instead of the result of calling the functions. That may or may not be convenient depending on how they are used in the sub-templates, but it will prevent them from both being run every time. Here is a simple example:
<template name="myTemplate">
{{> titleTemplate title}}
{{> descriptionTemplate description}}
</template>
<template name="titleTemplate">
<p>{{excitedTitle}}</p>
</template>
<template name="descriptionTemplate">
<p>{{this}}</p>
</template>
var getTitle = function() {
console.log('computed title');
return Session.get('title');
};
var getDescription = function() {
console.log('computed description');
return Session.get('description');
};
Router.map(function() {
this.route('home', {
path: '/',
template: 'myTemplate',
data: function() {
return {
title: getTitle,
description: getDescription
};
}
});
});
Meteor.startup(function() {
Session.setDefault('title', 'title1');
Session.setDefault('description', 'description1');
});
Template.titleTemplate.excitedTitle = function() {
return "" + (this.toUpperCase()) + "!";
};
From the console you can change the session variables (title and description) and you will see that only one function will be run at a time. I hope that helps.
One way to solve this is to not use the data context, but just use template specific helpers. Since I don't know what your getTitle and getDescription function do, I can't tell whether that is an option for you. It depends on whether you need to use the this object in those functions and need this to refer to the route object or not. If not, then the following seems like the better solution:
JS:
Router.map(function () {
this.route('myroute', {
path: '/route',
template: 'myTemplate'
});
});
Template.myTemplate.title = getTitle;
Template.myTemplate.description = getDescription;
HTML:
<template name="myTemplate">
{{> titleTemplate title}}
{{> descriptionTemplate description}}
</template>

Resources