在 Meteor JS 中重用部分代码

Reused part of code in Meteor JS

我有这个代码

Template['product'].helpers( 'variant': -> variant_value = Session.get('variant') if variant_value return variant_value else Session.set('variant',@lowest_variant()) 'isSelected': -> if @variant() == opt1_name return true else return false 我想在 isSelected 中使用变体方法。上面的代码不起作用。知道如何创建一个函数以便它可以用于不同的辅助方法吗?

但是如何创建一个函数以便它可以用于不同的辅助方法只需创建一个全局函数

我不是咖啡脚本方面的专家。

但是在 meteor 上,全局变量发生了这种情况,来自 docs

Per the usual CoffeeScript convention, CoffeeScript variables are file-scoped by default (visible only in the .coffee file where they are defined.)

因此,您在使用该助手的 .coffee 文件的顶层创建该函数。

纯粹javascript

 variant = function(){  
     //code to be used on diferents helpers
    }

您无法访问您的私有辅助方法的原因是它尚未创建。它被定义为对象的一部分,在定义后返回给 helpers() 方法。

它必须在该方法之外声明:

variant = () ->
  variant_value = Session.get('variant')
  if variant_value
    return variant_value
  else
    Session.set('variant',@lowest_variant())

Template['product'].helpers(
  'isSelected': ->
    if variant() == opt1_name
      return true
    else return false        

实际上我认为您正在寻找 Template.registerHelper() 函数

Template.registerHelper 'isSelected', ->
   return if variant() == opt1_name then true else false

请参阅文档 here

更新: 要在 CoffeeScript 中创建全局 Meteor 的应用程序变量,只需通过 @:

将其绑定到全局范围
@myGlobalVar = {}

或者将其绑定到 Meteor 对象:

Meteor.myGlobalVar = {}