JoeTidee
JoeTidee

Reputation: 26124

How do I get template object data to persist in Meteor templates?

I want to be able to set/get data of a template object when using template event handler functions. I have tried to set a variable at the point when the template is rendered and hoped it would be accessible later on, in this case when an element in the template is clicked by the users, but it isn't working:

<template name="fooBar">
    <div class="some_element">CLICK ME</div>
</template>

Template.fooBar.rendered = function(){
    this.templateVar = "Hello";
}

Template.fooBar.events({
    'click .some_element': function(e,t){
        alert(this.templateVar); // Should say 'Hello', but is 'undefined'.
    }
});

Upvotes: 1

Views: 171

Answers (2)

JoeTidee
JoeTidee

Reputation: 26124

As per the suggestion given by Sindis, this is the quickest way to solve the issue:

Instead of...

alert(this.templateVar); 

... just do...

alert(this.templateVar); or alert(Template.instance().templateVar);

Upvotes: 0

Ethaan
Ethaan

Reputation: 11376

Using reactive-dict package, you can do like this.

First add it.

meteor add reactive-dict

Second create the templates. (note im using meteor 1.1 version)

if (Meteor.isClient) {
  Template.hello.onRendered(function(){
       this.templateVar = new ReactiveDict(); //create the var templateVar
    })

   Template.hello.onRendered(function(){

     this.templateVar.set("hi", "hello"); //give them a value
   })

     Template.hello.events({
      'click .some_element': function(e,t){
         console.log(t.templateVar.get('hi')) //and print the value using the template instance.
      }
   });
 }

Upvotes: 2

Related Questions