What's the proper way for shared meteor templates methods


#1

I have methods (say function1, function2) which is common across different templates (say template1, template2). Right now i’m using Template.registerHelper to achieve that. But I need to call those function in certain intervals (say 2 mins). How to achieve that? Is Template.registerHelper is the correct way to do this (or) is there any other better way of doing this?

The sample code is given for better understanding. Thanks in advance.

Template1.html

<Template name="template1">
   {{function1}}
   {{function2}}
</Template>

Template2.html

<Template name="template2">
   {{function1}}
   {{function2}}
</Template>

Main.js

Template.registerHelper( 'function1', () => {
   //do something
});
Template.registerHelper( 'function2', () => {
   //do something
});

Doubt

Meteor.setInterval(function(){
  //How to call those template functions?
}, (60*1000)*2));

#2

Instead of using helpers you could use a session object or global reactiveVar. You run your function every 2 minutes and adjust that variable. When you use it in your templates they should be reactive.

You’ll still need to create a helper in the template to access the global var or session var.


#3

@nlammertyn : Thanks for your quick response. But i’m little lost here. Can you please explain me using sample problem given above. Please and Thank you.


#4

Here’s a simple example. If you want to learn more about Session, take a look at http://docs.meteor.com

// yourFunctions.js
Meteor.setInterval(function(){
    var function1Result = "abc";
    var function2Result = "123";

    // Do some stuff

    // Set your session variables
    Session.set("function1Result", function1Result);
    Session.set("function2Result", function2Result);
}, (60*1000)*2));

// yourTemplate.js
Template.yourTemplate.helpers({
    function1ResultHelper: function(){
        return Session.get("function1Result");
    },

    function2ResultHelper: function(){
        return Session.get("function2Result");
    },
});

// yourTemplate.html
<template name="yourTemplate">
    {{function1ResultHelper}} 
    {{function2ResultHelper}}
</template>