2014-10-16 62 views
5

从流星0.9.4开始,定义模板。 MyTemplateMyHelperFunction()不再有效。从模板的上下文中调用另一个助手的助手(流星0.9.4)

我们不推荐使用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(); 
} 

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

+0

我意识到这仍然是一个有效的问题,因为测试平台最好能够调用模板助手。否则,你最终会不必要地重写你的应用程序... – MrMowgli 2015-02-16 02:40:26

+0

你可能会觉得这个答案有用:https://stackoverflow.com/questions/27755891/meteor-what-is-spacebars-kw-hash-object#answer-27756461 – 2015-09-25 16:25:29

回答

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

顺便说一句,如果你发现你不断重复跨多个模板相同的帮手,它可以帮助使用Template.registerHelper,而不是分配相同功能的多个地方。

+0

这个紧密耦合你的代码。所有依赖于doCommonThing()的东西都必须知道它存在,以及它是如何被调用的。这是干的,但耦合。 – 2015-09-25 16:09:26

+0

你可能会觉得这个答案有用:https://stackoverflow.com/questions/27755891/meteor-what-is-spacebars-kw-hash-object#answer-27756461 – 2015-09-25 16:25:15

相关问题