在 Blaze 中重用代码

通常情况下,您可能希望在两个完全无关的组件之间重用代码。在 Blaze 中,主要有两种方法可以做到这一点。

组合

如果可能,通常最好尝试将需要共享功能的两个组件的可重用部分抽象成一个新的、更小的组件。如果您遵循 可重用组件 的模式,您应该可以轻松地在需要此功能的任何地方重用此子组件。

例如,假设您的应用程序中有很多地方需要在您单击“esc”键时将输入框模糊处理。如果您正在构建一个也需要此功能的自动完成小部件,您可以在 autocompleteInput 中组合一个 blurringInput

1
2
3
<template name="autocompleteInput">
{{> blurringInput name=name value=currentValue onChange=onChange}}
</template>
1
2
3
4
5
6
7
8
9
10
11
12
13
Template.autocompleteInput.helpers({
currentValue() {
// perform complex logic to determine the auto-complete's current text value
},
onChange() {
// This is the `autocompleteInput`'s template instance
const instance = Template.instance();
// The second argument to this function is the template instance of the `blurringInput`.
return (event) => {
// read the current value out of the input, potentially change the value
};
}
});

通过使 blurringInput 灵活且可重用,我们可以避免在 autocompleteInput 中重新实现功能。

通常最好让您的视图层尽可能薄,并将组件限制在其需要执行的特定任务。如果涉及到繁重的处理(例如复杂的数据加载逻辑),通常有意义将其抽象成一个库,该库只处理逻辑本身,而根本不处理 Blaze 系统。

例如,如果某个组件需要大量的复杂 D3 代码来绘制图表,那么这些代码本身很可能可以存在于一个单独的模块中,该模块由组件调用。这使得以后更容易抽象代码并在需要绘制图表的各种组件之间共享代码。

全局助手

共享常用视图代码的另一种方法是全局 Spacebars 助手。您可以使用 Template.registerHelper() 函数定义它们。通常,您注册助手来执行简单的事情(例如以特定格式呈现日期),这些事情并不需要单独的子组件。例如,您可以执行以下操作

1
2
3
Template.registerHelper('shortDate', (date) => {
return moment(date).format("MMM do YY");
});
1
2
3
4
5
6
<template name="myBike">
<dl>
<dt>Date registered</dt>
<dd>{{shortDate bike.registeredAt}}</dd>
</dl>
</template>
在 GitHub 上编辑