Search code examples
meteormeteor-blazespacebars

Updating a template on separate template event


I have a small meteor app. Inside there are two templates, one with a selector, and one with simple text. Anytime the selector is changed, I would like to get the second template to re-render. I'm a bit new to this, so any help would be appreciated.

Main.html

<head>
  <title>btn-test</title>
</head>

<body>
  <h1>Welcome to Meteor!</h1>

  {{> selector}}
  {{> display}}
</body>


<template name="selector">
    <select id="carSelector">
        <option value="volvo" selected="selected">Volvo</option>
        <option value="saab">Saab</option>
        <option value="mercedes">Mercedes</option>
        <option value="audi">Audi</option>
    </select>
</template>

<template name="display">
    {{selectorValue}}
</template>

Main.js

import { Template } from 'meteor/templating';
import { ReactiveVar } from 'meteor/reactive-var';

import './main.html';


Template.selector.events({
  'change #carSelector': function(event){
    return event.currentTarget.value
  }
});

Template.display.helpers({
  "selectorValue": function(){
    return $('#carSelector').val();
  }

});

Solution

  • You need to use a reactive data source to store the selected value, I see you already install ReactiveVar package so let use it:

    import { Template } from 'meteor/templating';
    import { ReactiveVar } from 'meteor/reactive-var';
    
    import './main.html';
    const selectedValue  = new ReactiveVar('');
    
    Template.selector.events({
      'change #carSelector': function(event){
        selectedValue.set(event.currentTarget.value);
      }
    });
    
    Template.display.helpers({
      "selectorValue": function(){
        return selectedValue.get();
      }
    
    });