How to use Meteor methods inside of a template helper

前端 未结 6 1440
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 12:05

How can I define a Meteor method which is also callable in a template helper?

I have these two files:

file: lib/test.js

Meteor.methods({
             


        
6条回答
  •  梦谈多话
    2020-11-22 12:49

    There is now a new way to do this (Meteor 0.9.3.1) which doesn't pollute the Session namespace

    Template.helloWorld.helpers({
        txt: function () {
            return Template.instance().myAsyncValue.get();
        }
    });
    
    Template.helloWorld.created = function (){
        var self = this;
        self.myAsyncValue = new ReactiveVar("Waiting for response from server...");
        Meteor.call('getAsyncValue', function (err, asyncValue) {
            if (err)
                console.log(err);
            else 
                self.myAsyncValue.set(asyncValue);
        });
    }
    

    In the 'created' callback, you create a new instance of a ReactiveVariable (see docs) and attach it to the template instance.

    You then call your method and when the callback fires, you attach the returned value to the reactive variable.

    You can then set up your helper to return the value of the reactive variable (which is attached to the template instance now), and it will rerun when the method returns.

    But note you'll have to add the reactive-var package for it to work

    $ meteor add reactive-var
    

提交回复
热议问题