Meteor.js - Calling a template helper within template rendered

时光怂恿深爱的人放手 提交于 2019-12-06 15:08:23

This isn't really the right way of going about things as the way Meteor works is by compiling templates before the application starts, rather than at run-time. Whilst something along these lines may be possible (for example by using Template.registerHelper), it would be much better to set a reactive variable to a specific value in the rendered callback and have the helper set to return that instead:

Session.setDefault('randomNum', 0);

Template.myTemplate.rendered = function () {
  Session.set('randomNum', Math.random());
}

Template.otherTemplate.helpers({
    randomNum: Session.get('randomNum')
});

If you'd rather use a private variable for the randomNum, have a look at ReactiveVar. It could be any reactive data source and it would work.

You used to create helpers as an object of the template but since Meteor has deprecated that you now have to create the helpers within the helper function.

Now in order to call the helper via javascript you must use this function

Template.*TemplateName*.__helpers.get('*HelperName*')(*Params*);

Its a pretty simple way of doing this and it keeps the functions out of the global scope so its pretty clean.

Here is an example of how I am using this

~~~

Template.home.events({
    'click .pair': function(event) {
        var _this = $(event.currentTarget);
        Template.home.__helpers.get('pairDevice')(_this);
    }
});

Template.home.helpers({
    'devices' : function() {
        return Session.get('devices');
    },
    'pairDevice' : function(elm) {
        elm.fadeOut();
        $('.home-page').addClass('paired');
        var deviceList = [
            {
                'name' : 'Patrick\'s Phone',
                'UUID' : '234123,4n123k4nc1l2k3n4 l1k23n4l12k3nc4l12'
            },
            {
                'name' : 'Mike\'s Phone',
                'UUID' : '734k23k4l2k34l2k34l2k34l2k3m'
            },
            {
                'name' : 'Edgar\'s Phone',
                'UUID' : '567k56l7k4l56k7l5k46l74k56l74k5'
            }
        ];
        Session.set('devices', deviceList);
    }
});

~~~

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!