繁体   English   中英

在模板的上下文中从另一个帮助器调用一个帮助器(Meteor 0.9.4)

[英]Calling one helper from another helper within the context of a template (Meteor 0.9.4)

截至Meteor 0.9.4,定义模板。 MyTemplate MyHelperFunction ()不再有效。

我们弃用了Template.someTemplate.myHelper = ...语法,转而使用Template.someTemplate.helpers(...)。 使用旧语法仍然有效,但它会向控制台输出弃用警告。

这对我来说似乎很好,因为它(至少)会保存一些错误输入和重复的文本。 但是,我很快发现我构建Meteor应用程序的方式倾向于这个新版本已弃用的功能。 在我的应用程序中,我一直使用旧语法定义助手/函数,然后从其他助手调用这些方法。 我发现它帮助我保持代码清洁和一致。

例如,我可能有这样的控件:

//Common Method
Template.myTemplate.doCommonThing = function()
{
    /* Commonly used method is defined here */
}

//Other Methods
Template.myTemplate.otherThing1 = function()
{
    /* Do proprietary thing here */
    Template.myTemplate.doCommonThing();
}

Template.myTemplate.otherThing2 = function()
{
    /* Do proprietary thing here */
    Template.myTemplate.doCommonThing();
}

但是Meteor建议的新方法似乎没有这个(这让我觉得我一直都错了)。 我的问题是, 在模板的助手之间共享通用的,模板特定的逻辑的首选方法什么?

对不起,如果我很沉闷,但是你不能将该函数声明为对象并将其分配给多个助手吗? 例如:

// Common methods
doCommonThing = function(instance) // don't use *var* so that it becomes a global
{
    /* Commonly used method is defined here */
}

Template.myTemplate.helpers({
    otherThing1: function() {
        var _instance = this; // assign original instance *this* to local variable for later use
        /* Do proprietary thing here */
        doCommonThing(_instance); // call the common function, while passing in the current template instance
    },
    otherThing2: function() {
        var _instance = this;
        /* Do some other proprietary thing here */
        doCommonThing(_instance);
    }
});

顺便说一句,如果您注意到您经常在多个模板中复制相同的帮助程序,则可能有助于使用Template.registerHelper而不是将相同的函数分配给多个位置。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM