在我的Meteor应用程序(v1.1.0.2)中,我有10个全球帮助者:
Template.registerHelper("getUser", function(id) {
return Meteor.users.findOne({
_id: id
});
});
Template.registerHelper("getPublication", function(id) {
return Publications.findOne({
_id: id
});
});
Template.registerHelper("getCategory", function(id) {
return Categories.findOne(new Mongo.ObjectID(id));
});
Template.registerHelper("getAge", function(id) {
return Ages.findOne(new Mongo.ObjectID(id));
});
Template.registerHelper("getPhoto", function(id) {
return new FS.File(ImagesPublications.findOne({
_id: id
}));
});
Template.registerHelper("optionsCategories", function(id) {
return Categories.find().map(function(element) {
return {
label: element.name,
value: element._id._str
};
});
});
Template.registerHelper("optionsAges", function(id) {
return Ages.find().map(function(element) {
return {
label: element.name,
value: element._id._str
};
});
});
Template.registerHelper("allowedCategories", function(id) {
return Categories.find().map(function(element) {
return element._id._str;
});
});
Template.registerHelper("allowedAges", function(id) {
return Ages.find().map(function(element) {
return element._id._str;
});
});
Template.registerHelper("prettifyDate", function(date) {
return moment(date).format('L HH:mm:ss');
});
我试图使用对象在单个函数调用中压缩所有这些:
Template.registerHelper({
getUser: function(id) {
return Meteor.users.findOne({
_id: id
});
},
getPublication: function(id) {
return Publications.findOne({
_id: id
});
},
getCategory: function(id) {
return Categories.findOne(new Mongo.ObjectID(id));
},
getAge: function(id) {
return Ages.findOne(new Mongo.ObjectID(id));
},
getPhoto: function(id) {
return new FS.File(ImagesPublications.findOne({
_id: id
}));
},
optionsCategories: function(id) {
return Categories.find().map(function(element) {
return {
label: element.name,
value: element._id._str
};
});
},
optionsAges: function(id) {
return Ages.find().map(function(element) {
return {
label: element.name,
value: element._id._str
};
});
},
allowedCategories: function(id) {
return Categories.find().map(function(element) {
return element._id._str;
});
},
allowedAges: function(id) {
return Ages.find().map(function(element) {
return element._id._str;
});
},
prettifyDate: function(date) {
return moment(date).format('L HH:mm:ss');
}
});
我尝试了上述内容但没有成功,所以我想知道我是否可以做类似的事情。
答案 0 :(得分:4)
当然,只需将你的助手放在一个键/值字典中,如下所示:
var helpers = {
getAge: function(id) {
return Ages.findOne(new Mongo.ObjectID(id));
}
};
然后使用循环迭代每对并在内部注册帮助程序。
_.each(helpers, function(value, key){
Template.registerHelper(key, value);
});