user3676943
user3676943

Reputation: 923

In Meteor How to copy data between templates?

I'm new to both meteor and JS.

I created a meteor app like this:

cd /tmp/
meteor create hello
cd hello

In hello.html I wrote this

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

  {{> t1}}
  {{> t2}}
</body>

Then I added these templates:

<template name='t1'>
<span id='t1'>hello</span>
</template>

<template name='t2'>
<span id='t2'>world</span>
</template>

Then I wrote syntax inside of hello.js to get text from the DOM:

Template.t1.onRendered( function() {
  mytext = $('span#t1').html() }); 

According to the debugger-console in my browser, the above syntax works okay.

The debugger tells me that mytext == 'hello'

Question: How to share the mytext value with other parts of my Meteor app?

As written, mytext is stuck inside my anonymous function.

For example how would I make this call work:

$('span#t2').html(mytext)

??

Upvotes: 0

Views: 289

Answers (1)

Carson Moore
Carson Moore

Reputation: 1287

You'll want to reactively watch your variable. An easy out-of-the-box solution for this is to use the Session variable. You can do it pretty easily like so:

Template.t1.onRendered( function() {
  Session.set('mytext', $('span#t1').html()); 
}); 

Then in your second template, define and reference helper that returns that variable:

<!--html-->
<template name='t2'>
  <span id='t2'>{{getMyText}}</span>
</template>

//js
Template.t2.helpers({
  getMyText: function() { return Session.get('mytext'); }
});

The Session variable is reactive, so when the first template renders and sets the value of Session.mytext, the helper's result will be invalidated and the second template will update.

Upvotes: 1

Related Questions