How to use Meteor methods inside of a template helper

前端 未结 6 1442
伪装坚强ぢ
伪装坚强ぢ 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:58

    Methods on the client side are asynchronous, and their return value is always undefined. To get the actual value returned by the method, you need to provide a callback:

    Meteor.call('method', 'argument', function(error, result) {
        ....
    });
    

    Now, there's no easy way to use the result in your helper. However, you can store it in your template as a data object and then return it in the helper:

    Template.template.created = function() {
        var self = this;
        self.data.elephantDep = new Deps.Dependency();
        self.data.elephant = '';
        Meteor.call('getElephant', 'greenOne', function(error, result) {
            self.data.elephant = result;
            self.data.elephantDep.changed();
        });
    };
    
    Template.template.showElephant = function() {
        this.elephantDep.depend();
        return this.elephant;
    };
    

提交回复
热议问题