【问题标题】:Calling external functions from Meteor Template helpers从 Meteor 模板助手调用外部函数
【发布时间】:2015-09-14 20:09:42
【问题描述】:

我正在尝试在 Meteor 中构建一个适度可重用的复杂组件。它将包含在具有相似数据结构的多个模板中,我正在尝试实现类似 Angular 指令的功能。

数据上下文如下所示:

var post = {
    title: 'A test post',
    author: 'Joe Bloggs',
    bookmarked: true,
    bookmarkCount: 25
}

在 HTML 模板中我有这样的东西:

<template name="postDetail">
    <div class="jumbotron">
       <h3>{{title}}</h3>
       {{> footerLinks}}
    </div>
</template>

footerLinks 模板是我现在尝试构建的可重用组件。我希望它尽可能独立,并具有自己的 js 逻辑。一个简化的版本是:

<template name="footerLinks">
   {{author}} · {{formattedBookmarkCount}}
</template>

{{author}} 直接来自数据上下文。我想使用一个函数来构建书签计数的文本。令人惊讶的是,这不起作用,它甚至不返回默认值。

Template.footerLinks.helpers({
   updatedAt: 'wow',
   formattedBookmarkCount: function () {
      switch (bookmarkCount) {
         case 0:
            return "No bookmarks";
         case 1: 
            return "1 bookmark";
         default:
            return bookmarkCount + " bookmarks";
         } 
      }
   });

但无论如何,我希望让实际的帮助程序保持简单并引用外部函数。例如:

Template.footerLinks.helpers({
   updatedAt: 'wow',
   formattedBookmarkCount: formatBookmarks(bookmarkCount)
});

.... somewhere else ....
function formatBookmarks(bookmarkCount) {
    // call another function 
    return calcMessage(bookmarkCount);
}

function calcMessage(bookmarkCount) {
    return bookmarkCount + " bookmarks";
}

为了更进一步,我想在子函数中访问其他 Meteor 集合。

部分答案

感谢 @steph643 指出 this 的用法。下面的代码现在可以工作了:

Template.footerLinks.helpers({
   updatedAt: 'wow',
   formattedBookmarkCount: function() {
      switch (this.bookmarkCount) {
         case 0:
            return "No bookmarks";
         case 1: 
            return "1 bookmark";
         default:
            return this.bookmarkCount + " bookmarks";
         }
   },

但是我想把这个逻辑移到别处,并可能这样称呼它(这不起作用):

Template.footerLinks.helpers({
    updatedAt: 'wow',
    formattedBookmarkCount: formatBookmarks()
}

Template.registerHelper('formatBookmarks', function() {  
   return this.bookmarkCount + " bookmarks"; 
}

这将返回一个错误

Uncaught ReferenceError: formatBookmarks is not defined

【问题讨论】:

  • 在助手中,尝试使用“this.bookmarkCount”而不是“bookmarkCount”。

标签: meteor


【解决方案1】:

这主要是一个 javascript 的东西。当你注册一个助手时,你传入了一个里面有一堆方法的对象,而 Meteor 会发挥它的魔力,并将它们放在反应式上下文中。如果你想在 helpers 中使用这个函数,然后像你做的那样使用一个 global helper,只需将 global 重命名为你想要的并删除 local helper。

第二种选择是创建一个全局函数并通过助手调用它。

window.formatCount = function(count, singular, plural) {
  switch (count) {
    case 0:
      return "No " + plural;
    case 1:
      return count + ' ' + singular;
    default:
      return count + ' ' + plural;
  }
};

Template.registerHelper('formatBookmarksCount', function() {  
   return window.formatCount(this.bookmarkCount, 'bookmark', 'bookmarks')
}

现在您可以在客户端的任何位置使用它,并且您可以考虑对全局对象进行命名空间以避免使用 window(如果您愿意)(关于此的大量帖子)。

【讨论】:

    猜你喜欢
    • 2016-05-26
    • 2014-01-08
    • 2015-01-06
    • 2014-11-27
    • 2013-02-18
    • 2016-04-22
    • 2015-09-20
    • 2014-08-12
    • 2016-03-04
    相关资源
    最近更新 更多