Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
144 views
in Technique[技术] by (71.8m points)

javascript - How to use Meteor methods inside of a template helper

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({
    viewTest : function (str) {
        return str;
    }
});

file: client/myView.js

Template.helloWorld.helpers({
    txt : function () {
        var str = Meteor.call('viewTest', 'Hello World.');
        return str;
    }
});

When I give "str" a normal string everything works fine. But in this case my template does not get any value. I defined - for the test - in the same file where the method is a normal function and tried to call the function. The error I got was that the function does not exist. So I think that Meteor tries to render the template before it knows anything about the methods I defined for it. But I think that this is a bit unusual - isn't it?

question from:https://stackoverflow.com/questions/22147813/how-to-use-meteor-methods-inside-of-a-template-helper

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...