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

Dom*_*rez 5 javascript templates meteor

截至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();
}
Run Code Online (Sandbox Code Playgroud)

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

小智 3

抱歉,如果我很迟钝,但是您不能将函数声明为对象并将其分配给多个助手吗?例如:

// 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);
    }
});
Run Code Online (Sandbox Code Playgroud)

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