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

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

问题描述

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

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

我有这两个文件:

文件:lib/test.js

file: lib/test.js

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

文件: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),它不会污染 Session 命名空间

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 的新实例(参见 docs)并将其附加到模板实例.

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天全站免登陆