Reputation: 472
Let's say I have a templateA.html
with input fields and then another separate templateB.html
which is supposed to display the values of the input fields from templateA.html
as they are typed in. I've gotten it to work with Session.set and Session.get
but the problem is the input values stay the same when the page is refreshed and it doesn't seem the best way to do this. I then tried to use ReactiveVar
but since I can't find any good examples on how to use it I'm a bit lost. The following is how it works with Session
so maybe this will help understand what I'm trying to do with ReactiveVar
.
Template.templateA.events({
'change #batch_form': function(){
var batch_num = document.getElementById('batch_number').value;
var dist_name = document.getElementById('distributor_name').value;
var data = {
batch_number: batch_num,
dist_name: dist_name
}
Session.set('form_data', data);
}
})
Template.templateB.helpers({
input_data(){
return Session.get('form_data');
},
});
TemplateB.html
<template name='templateB'>
<p>Batch #:{{input_data.batch_number}}</p>
<p>Batch #:{{input_data.dist_name}}</p>
</template>
Upvotes: 0
Views: 306
Reputation: 8413
You should avoid Session
where you can. Better scope your Template-exceeding variables with a shared scope. ES6 import/export are suitable for that.
Consider you want to share a ReactiveDict
(which behaves like Session
) as state between only those two Templates. You can create a new js file with the following content:
shared.js
import { ReactiveDict } from 'meteor/reactive-dict'
export const SharedAB = new ReactiveDict()
This gives you the control to share the state only between those Templates, that import the object.
templateA.js
import { SharedAB } from './shared.js'
Template.templateA.events({
'change #batch_form': function(){
var batch_num = document.getElementById('batch_number').value;
var dist_name = document.getElementById('distributor_name').value;
var data = {
batch_number: batch_num,
dist_name: dist_name
}
SharedAB.set('form_data', data);
}
})
templateB.js
import { SharedAB } from './shared.js'
Template.templateB.helpers({
input_data(){
return SharedAB.get('form_data');
},
});
Upvotes: 1
Reputation: 3043
if they don't have any parent-child relationship you can use common ReactiveDict variable(here Session
) to pass the data between just like you're doing.
but the problem is the input values stay the same when the page is refreshed and it doesn't seem the best way to do this
for this on onDestroyed
callback of template you can clear the Session
variable values
Template.templateA.onDestroyed(function(){
Session.set('form_data', false); // or {}
})
so when you come back to this page/template, there is no data to display.
Upvotes: 1