我想创建全局函数来从Meteor中删除我的集合中的项目。
我的代码:
Template.adminLayout.events({
'click .delete': function(e) {
var collection = $(e.target).data('collection'),
redirect = $(e.target).data('redirect'),
id = this._id;
// Remove request
collection.remove(id);
// Redirect
Router.go(redirect);
}
});
使用collection.remove(id)
,我收到此错误:
collection.remove不是函数
如果我使用消息(我的收藏品名称)Messages.remove(id)
进行测试,则可以正常使用。
你知道为什么我的代码不起作用吗?
答案 0 :(得分:2)
您的collection
参数是一个包含集合名称的字符串,而不是集合本身。您需要实际的集合对象来执行数据操作。如果您希望能够按名称访问集合,则需要自己准备字典。例如:
Collections = {};
Collections['Documents'] = Documents = new Mongo.Collection('documents');
然后您可以在事件处理程序中使用它:
var collection = Collections[$(e.currentTarget).data('collection')];
顺便说一下,最好使用e.currentTarget
代替e.target
。它始终为您提供所期望的元素,而e.target
可以是其后代之一。