I\'m rendering the same Handlebars template in multiple (arbitrarily many) locations on the same page. Inside each template, I want a button to toggle the visibility of a di
This is how I achieved a per-template instance reactive source
I only want to ask the user for the reason for a dinosaur's extinction when its extinction status is set to extinct.
{{#if isExtinct extinctStatus newExtinctStatus extinctStatusDep}}
{{/if}}
To reactively display the reason field, we add a Deps.Dependency
to this.data
in the template created
function
Template.dinosaur.created = function() {
this.data.newExtinctStatus = null;
this.data.extinctStatusDep = new Deps.Dependency;
};
We listen for when the user changes the extinction status selection, and update the newExtinctStatus
and called changed
on our extinctStatusDep
.
Template.dinosaur.events({
'change [name="extinction-status"]': function(event, template) {
var extinctStatus = $(event.target).val();
template.data.newExtinctStatus = extinctStatus;
template.data.extinctStatusDep.changed();
}
});
In the helper we say we depend on the Deps.Dependency
we are passed
Template.dinosaur.helpers({
isExtinct: function(status, newStatus, statusDep) {
if (statusDep) {
statusDep.depend();
}
if (newStatus) {
if (newStatus == 'extinct') {
return true;
}
else if (status == 'extinct') {
// No new status is set, so use the original.
return true;
}
}
});
It is a bit of a hack involving adding to this.data
, but it allows for per-template reactivity, useful for when you rely on data that has not been saved to something in a Collection
yet.