aquavitae
aquavitae

Reputation: 19114

Dynamic calculated values in meteor templates

I am trying to grasp something that I'm sure is pretty basic in meteor, i.e. using reactive calculated values. Here is a simple example of the sort of thing I am trying to acheive. The code doesn't work, but it looks something like what I would expect might work. I am using autoform for schema validations

Schema = {}
Schema.calcs = new SimpleSchema({
    a: {type: Number},
    b: {type: Number}
});

Template.Calcs.helpers({
    total: function() {
        var a = Autoform.getFieldValue('calcs', 'a')
        var b = Autoform.getFieldValue('calcs', 'b');
        // Would be nice if I could do something like this instead of the above
        // var a = this.Autoform.a;
        // var b = this.Autoform.b;
        return a + b;
    },
    totalDouble: function() {
        var total = this.total;  // This doesn't work
        return total * 2;
    }
});

The template looks something like:

<template name='calcs'>
  {{> quickForm id="calcs" schema="Schema.calcs" validation="keyup"}}
  <ul>
    <li>Total: {{total}}</li>
    <li>Double Total: {{totalDouble}}</li>
  <ul>
</template>

I have 3 questions:

  1. How do get the value of another helper in code?
  2. Is there a cleaner way than Autoform.getFieldValue(...) to get entered values in the helper?
  3. Is this actually the best way of achieving what I want with Meteor?

This is actually a test project I'm migrating from Ember, and the behaviour I'm after is implemented in an Ember controller (excluding validation) like this:

App.CalcsController = Ember.Controller.extend({
    a: null,
    b: null,

    total: function() {
        return this.get('a') + this.get('b');
    }.property('a', 'b'),

    totalDouble: function() {
        return this.get('total') * 2;
    }.property('total')
});

Upvotes: 1

Views: 328

Answers (1)

Marius Darila
Marius Darila

Reputation: 873

You can store it in session:

total: function() {
    var a = parseInt(Autoform.getFieldValue('calcs', 'a'))
    var b = parseInt(Autoform.getFieldValue('calcs', 'b'));
    var total = a+b;
    Session.set("total", total);
    return total;
    },
totalDouble: function(){
    var total = Session.get("total");
    return  total* 2;
}

Upvotes: 1

Related Questions