Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get reactive var from another template in Meteor

I have a template with some nested templates in Meteor:

<template name="collectingTmpl">
  {{> firstTmpl}}
  {{> secondTmpl}}
</template>

If I set a reactive var/dict in firstTmpl with

Template.firstTmpl.events({
  'click .class-name': function(event, template) {
    template.state = new ReactiveDict;
    template.state.set('someName', 'someValue');
  }
});

I can get this value within the same template with

Template.firstTmpl.helpers({
  myValue: function() {
    Template.instance().state.get('someName');
  }
});

but can I also retrieve the value being set in firstTmpl from secondTmpl?

I mean something like

Template.secondTmpl.helpers({
  myValueFromAnotherTmpl: function() {
    Template.firstTmpl.state.get('someName');
  }
});
like image 717
mortensen Avatar asked Jul 24 '15 15:07

mortensen


2 Answers

You could alternatively set the ReactiveDict on the parent template which is collectingTmpl.

// always initialize your template instance properties
// in an onCreated lifecycle event
Template.collectingTmpl.onCreated(function(){
  this.firstTmplState = new ReactiveDict();
});

Then you can obtain references to this template instance property in child templates using this code :

Template.firstTmpl.onCreated(function(){
  // warning, this line is depending on how many parent templates
  // the current template has before reaching collectingTmpl
  var collectingTmplInstance = this.view.parentView.templateInstance();
  this.firstTmplState = collectingTmplInstance.firstTmplState;
});

Template.secondTmpl.onCreated(function(){
  var collectingTmplInstance = this.view.parentView.templateInstance();
  this.firstTmplState = collectingTmplInstance.firstTmplState;
});

Then you can use the standard Template.instance().firstTmplState syntax in any of your 3 templates and they'll always point to the same ReactiveVar instance defined as a property of collectingTmpl.

like image 177
saimeunt Avatar answered Oct 19 '22 10:10

saimeunt


If you take care on a currently issue of blaze (missing data context), you are able to access other templates vars by Template.parentData().

See this MeteorPad as a demo, the background color will be changed onn each player when pressing the button. the color is defined by their parent template:

http://meteorpad.com/pad/zoiAvwuT3XXE5ruCf/Leaderboard_Template_parentData_Bug

You may also read at GitHub PullRequest about some updates I suggest

https://github.com/meteor/meteor/pull/4797

Cheers Tom

like image 24
Tom Freudenberg Avatar answered Oct 19 '22 11:10

Tom Freudenberg