Julien Leray February 2016

Get template data from helper

I'm trying to update my template's datacontext on the onCreated hook:

Template.segment.onCreated(function () {
  var tp = this;

  this.test = "TEST";
  Meteor.call('getTreeCategData', function (error, data) {
    tp.ExternalapiData = data;
    tp.chart = new Chart(); 
    //...
  });
});

I want to keep these references on parents templates, To access them from childs templates.

Now I "update" a datacontext with the value set on the onCreated.

Template.segment.helpers({
  parentDatacontext: function(){
    this.chart = Template.instance().chart; //undefined
    this.apiData = Template.instance().apiData; //undefined
    //But it executed later, when I open the chrome object inspector    the reference, they are not undefined anymore 
    console.log("parentDatacontext: ", Template.instance());
    return this;
  }
});

My template:

<template name="segment">
{{#with parentDatacontext}}
{{> childtp}}
{{/with}}
</template>

To finally use them on child template event's handler:

Template.childtp.events({
    'click .js-close': function(e, tp){
        console.log(" tp parent data: ",Template.parentData(1));
    }
});

I'm actually stuck really soon on this process, i'm not even able to print the added attribute set on the onCreated from the helper... I guess the helper is call by the template before the on created end...

Any idea how to fix that, or a better way to do what I want to do?

Thanks

Answers


Stephen Woods February 2016

parentDataContext() is being executed before your Meteor.call is coming back, and then because your variables aren't reactive the helper doesn't get executed again. You want to use a reactive variable to store those values so the helper gets executed when the values get set by the method.

To access the new reactive variable in the child template, follow along with this forum post.


Radosław M February 2016

How about ReactiveVar?

Template.segment.onCreated(function () {
  var tp = this;

  this.apiData = new ReactiveVar();
  Meteor.call('getTreeCategData', function (error, data) {
    tp.apiData.set(data);
    tp.chart = new Chart();
    //...
  });
});

Template.segment.helpers({
  parentDatacontext: function(){
    this.chart   = Template.instance().chart;
    this.apiData = Template.instance().apiData.get();

    //    data - {{with parentDatacontext}}
    // no data - {{else}}
    if (this.apiData) {
        return this;
    }
  }
});

And template code

<template name="segment">
    {{#with parentDatacontext}}
        {{> childtp}}
    {{else}}
        Loading or something...
    {{/with}}
</template>

Post Status

Asked in February 2016
Viewed 2,851 times
Voted 11
Answered 2 times

Search




Leave an answer