【问题标题】:Calling one helper from another helper within the context of a template (Meteor 0.9.4)在模板上下文中从另一个助手调用一个助手 (Meteor 0.9.4)
【发布时间】:2014-12-12 10:40:31
【问题描述】:

从 Meteor 0.9.4 开始,定义 Template.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 建议的新方法(这让我一直认为我错了)。我的问题是,在模板的帮助程序之间共享通用的模板特定逻辑的首选方式是什么?

【问题讨论】:

  • 我意识到这仍然是一个有效的问题,因为测试台最好能够调用模板助手。否则你最终会不必要地重写你的应用程序......
  • 您可能会发现这个答案很有用:stackoverflow.com/questions/27755891/…

标签: javascript templates meteor


【解决方案1】:

对不起,如果我很无聊,但您不能将函数声明为对象并将其分配给多个助手吗?例如:

// 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 而不是将相同的函数分配给多个位置可能会有所帮助。

【讨论】:

  • 这会紧密耦合您的代码。所有依赖 doCommonThing() 的东西都必须知道它的存在,以及它是如何被调用的。它是干燥的,但是是耦合的。
  • 您可能会发现这个答案很有用:stackoverflow.com/questions/27755891/…
猜你喜欢
  • 2019-04-07
  • 1970-01-01
  • 2015-03-28
  • 2016-09-02
  • 2013-06-18
  • 1970-01-01
  • 1970-01-01
  • 2014-11-28
  • 1970-01-01
相关资源
最近更新 更多