如何在模板助手中使用Meteor方法 [英] How to use Meteor methods inside of a template helper

查看:162
本文介绍了如何在模板助手中使用Meteor方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何定义一个也可以在模板助手中调用的Meteor方法?

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

我有这两个文件:

file:lib / test.js

file: lib/test.js

Meteor.methods({
    viewTest : function (str) {
        return str;
    }
});

file:client / myView.js

file: client/myView.js

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

当我给str一个普通字符串时,一切正常。但在这种情况下,我的模板没有任何价值。我定义 - 测试 - 在同一个文件中,该方法是一个正常的函数,并试图调用该函数。我得到的错误是该函数不存在。所以我认为Meteor会在它知道我为它定义的方法之前尝试渲染模板。但我认为这有点不寻常 - 不是吗?

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?

推荐答案

现在有一种新方法可以做到这一点( Meteor 0.9.3.1)不会污染会话命名空间

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);
    });
}

在'created'回调中,您创建一个ReactiveVariable的新实例(请参阅文档)并将其附加到模板实例。

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.

但请注意,你必须为它添加reactive-var包工作

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

$ meteor add reactive-var

这篇关于如何在模板助手中使用Meteor方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆