user5074177
user5074177

Reputation: 43

Get ReactiveVar in anonymous function

I am using meteor reactive-var package. How can i get reactive variable in a anonymous function that is defined in templates's js file? viewer.js:

Template.viewer.helpers({
    counter: function () {
        return Template.instance().counter.get();
    }
});

Template.viewer.onCreated(function() {
    this.counter =  new ReactiveVar(0);
});

Template.viewer.onRendered(function(e){
    viewerRendered();
});

function getCounter() {
    // !!Return reactive counter variable
}

function viewerRendered() {
    var counter = getCounter();
    $(document).trigger("ViewerCreated",counter);
}

Thanks.

Upvotes: 1

Views: 146

Answers (1)

Kyll
Kyll

Reputation: 7139

If you need to access the current template in an external function through the onRendered() callback, you have multiple ways:

  1. Using the external function as a direct callback :

    Template.viewer.onRendered(viewerRendered)
    
    function viewerRendered() {
      let currentTemplate = this
      //...
    }
    
  2. Passing the current template as parameter :

    Template.viewer.onRendered(function() {
      viewerRendered(this)
    })
    
    function viewerRendered(currentTemplate) {
      //...
    

JavaScript functions are quite flexible since this is dynamic, there is other ways to access the data.
The two above are simple use-cases.

You may do whatever you want with the template such as accessing its data, using subscriptions...

Upvotes: 1

Related Questions