javascript - 在 Meteor 中访问父助手

标签 javascript meteor

我经常发现自己将我的工作分成仍然可以使用相同助手的模板。

所以,假设我有这个模板结构:

<template name="MainTemplate">
  <div>{{> FirstTemplate}}</div>
  <div>{{> SecondTemplate}}</div>
  <div>{{> ThirdTemplate}}</div>
  <div>{{> FourthTemplate}}</div>
</template>

现在这些模板中的每一个都想使用相同的助手,我们称它为dataHelper:

Template.MainTemplate.helpers({
  dataHelper: function() {
    //do some stuff
    return result
  }
})

遗憾的是,无法通过简单地键入 {{dataHelper}} 在模板 first 到 fourth 中访问此助手,就像事件的工作方式一样。

我的解决方案是创建一个全局助手,但这似乎有点矫枉过正,特别是因为我有几个页面根本不关心这些助手。另一种解决方案是创建四个独立的助手,但是,嘿,DRY。

我是不是漏掉了一些简单的东西?

最佳答案

在当前版本的 meteor 中没有明显的方法可以做到这一点。一种解决方案是让子模板“继承”父模板的助手。您可以使用 meteor-template-extension 轻松完成此操作.这是一个例子:

html

<body>
  {{> parent}}
</body>

<template name="parent">
  <h1>parent</h1>
  {{> child}}
</template>

<template name="child">
  <h2>child</h2>
  <p>{{saySomething}}</p>
</template>

js

Template.parent.helpers({
  saySomething: function() {
    return Random.choice(['hello', 'dude!', 'i know right?']);
  }
});

Template.child.inheritsHelpersFrom('parent');

模板 child 继承了其父级的所有助手,因此它可以直接访问 saySomething

这种技术有两个缺点:

  • 您必须指定inheritsHelpersFrom 关系
  • 所有 parent 的助手都是继承的

关于javascript - 在 Meteor 中访问父助手,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30922695/

相关文章:

即时创建 Javascript 对象

javascript - CSS 或 JS - 删除内联元素的默认横向空格

meteor - 从方法调用 Accounts.createUser 不会登录用户

meteor - 避免使用 Session.set

mongodb - 如何将生产 meteor js 数据库与开发同步?

javascript - Parsejs Angular/ ionic 检索 View 中的关系对象(第二次打开页面时显示值)

javascript - 按钮在后续选项卡上无法在 Highcharts 中重绘图表

javascript - 检查嵌套对象是否包含特定键,然后替换父对象的键

javascript - 使用 MySQL 安装/运行 Meteor 时出错

javascript - 如何在 Meteor 中取消注册集合?