我的模板助手有重复的代码:
Template.foodMenu.helpers({
breakfast: function() {
var breakfastItems = EatingTimes.find(// query for breakfast items);
// function to sort breakfastItems in here (code duplication)
},
lunch: function() {
var lunchItems = EatingTimes.find(// query for lunch items);
// function to sort lunchItems in here (code duplication)
},
dinner: function() {
var dinnerItems = EatingTimes.find(// query for dinner items);
// function to sort breakfastItems in here (code duplication)
}
);
我想干嘛:
Template.foodMenu.helpers({
breakfast: function() {
var breakfastItems = EatingTimes.find(// query for breakfast items);
sortFoodItems(breakfastItems);
},
lunch: function() {
var lunchItems = EatingTimes.find(// query for lunch items);
sortFoodItems(lunchItems);
},
dinner: function() {
var dinnerItems = EatingTimes.find(// query for dinner items);
sortFoodItems(dinnerItems);
}
);
我在哪里放置此功能以便干涸?如何命名空间,以便我可以正确地调用它?如果有所作为,我正在使用Iron Router。
var sortFoodItems = function (foodItems) {
// code to sort out and return foodItems to particular method that calls it
};
答案 0 :(得分:1)
只需在同一个文件中的助手之前定义你的功能
var sortFoodItems = function (foodItems) {
// code to sort out and return foodItems to particular method that calls it
};
Template.foodMenu.helpers({
breakfast: function() {
var breakfastItems = EatingTimes.find(/* query for breakfast items */);
sortFoodItems(breakfastItems);
},
lunch: function() {
var lunchItems = EatingTimes.find(/* query for lunch items */);
sortFoodItems(lunchItems);
},
dinner: function() {
var dinnerItems = EatingTimes.find(/* query for dinner items */);
sortFoodItems(dinnerItems);
}
});
如果要在多个文件中使用sortFoodItems函数,请创建名为lib的文件夹,并将该函数放在没有var关键字的文件functions.js中,以使其成为全局文件。例如:
//lib/functions.js
sortFoodItems = function (foodItems) {
// code to sort out and return foodItems to particular method that calls it
};
您需要了解Meteor如何读取您的项目目录。在Meteor文档中阅读有关structuring your application的更多信息。
答案 1 :(得分:1)
您还可以使用Template.registerHelper(name, function)
创建一个全局帮助器,如下所示:
Template.registerHelper('menuItems', function(eatingTime, sortCriteria) {
//do some checking of your arguments
eatingTime = eatingTime || '/* your default eating time */';
sortCriteria = sortCriteria || {/* your default sort criteria */};
check(eatingTime, String);
check(sortCriteria, Object);
//find and sort your items in one mongo query or you could do separate find and sort if you want
menuItems = EatingTimes.find({time: eatingTime}, sortCriteria);
return menuItems;
});
这将是干扰您代码的最 meteoric 方式。
然后在您的模板中,您可以将其命名为:
{{#each menuItems 'time args' 'sort arg'}}