【发布时间】: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