Reputation: 41
I have a Meteor project where two different templates depend on data from the same document:
{ "title": "My Project", "data": "My project data" }
One template renders the "title", and another renders the "data".
If a user changes the "data" field in the document, I do not want the template that uses the "title" field to re-render. I only want the template that uses "data" to re-render.
For example, the title may be in a page header which does not need to be re-rendered if the project's data changes.
How can this be achieved?
My Meteor templates:
<head>
<title>experiment</title>
</head>
<body>
{{>hello}}
</body>
<template name="hello">
<div>
My projects.
</div>
{{#each projects}}
<div>
{{>projectTitle}}
{{>projectData}}
</div>
{{/each}}
</template>
<template name="projectTitle">
<div>
Project title: {{title}}
</div>
</template>
<template name="projectData">
<div>
Project data: {{data}}
</div>
</template>
My Meteor Javascript:
Experiments = new Meteor.Collection("experiments");
if (Meteor.isClient) {
Template.hello.projects = function() {
return Experiments.find();
}
Template.projectTitle.title = function() {
return Experiments.find().fetch()[0].title;
}
Template.projectData.data = function() {
return Experiments.find().fetch()[0].data;
}
Template.projectTitle.rendered = function() {
console.log('Rendered projectTitle');
}
Template.projectData.rendered = function() {
console.log('Rendered projectData');
}
}
This code will currently output "Rendered projectTitle" and "Rendered projectData" whenever either of the fields in the Project document change, which shows that both templates are being re-rendered.
Edit I don't know if there is a 'correct' way to do this, but one could publish two subscriptions, which return separate parts of the document. This seems counter to the philosophy of Meteor, though.
Upvotes: 1
Views: 161
Reputation: 32698
You can make your templates read from a Session
variable, and then set the Session variable appropriately using Meteor.autorun
.
Then when your object changes, Meteor.autorun
will execute again, but the Session won't change if the field didn't change.
Upvotes: 2