Setting a variable within a template event handler and reactively updating the UI


#1

Here’s my simple template.

<template name="landingSignup">
  <form class="form-inline">
    <input type="email" name="email"/>
    <input type="password" name="password">
    <input type="submit" value="Submit">

    <p>Whoops! {{reason}}</p>
  </form>
</template>

And my handler:

Template.landingSignup.events({
  'submit form': function(event) {
    event.preventDefault();
    var email = event.target.email.value;
    var password = event.target.password.value;

    if (email !== "" && password !== "") {
      Meteor.loginWithPassword(email, password, function(error) {
        if (error && error.reason === "Incorrect password") {
          console.log("Should set the {{reason}} variable here.");
        }
      }
    }
  }
});

How can I set the {[reason}} variable in my event handler?


#2

You can use a ReactiveVar and assign a value in the event handler and then use the ReactiveVar in your template helper.


#3

Try if this works

Template.landingSignup.onCreated(function(){
 this.reason = new ReactiveVar("");
});
Template.landingSignup.events({
  'submit form': function(event, template) {
    event.preventDefault();
    var email = event.target.email.value;
    var password = event.target.password.value;

    if (email !== "" && password !== "") {
      Meteor.loginWithPassword(email, password, function(error) {
        if (error && error.reason === "Incorrect password") {
          template.reason.set(error.reason);
          console.log("Should set the {{reason}} variable here.");
        }
      }
    }
  }
});

#4

Yeah adding a ReactiveVar fixed the issue. Thanks for the help guys.