您需要使用ReactiveVar 来存储当前点击的项目。
首先你需要运行meteor add reactive-var,因为它不是标准meteor web应用默认添加的包。
JS:
Template.adminManageCategories.created=function(){
// instantiate the reactive-var in the created callback
// we store it as a property of the template instance
this.currentItemId=new ReactiveVar(null);
};
Template.adminManageCategories.helpers({
// this helper reactively returns the currently clicked item
currentItem:function(){
// retrieve the reactive-var from the template instance...
var currentItemId=Template.instance().currentItemId.get();
// ...to fetch the correct collection document
return Items.findOne(currentItemId);
}
});
Template.adminManageCategories.events({
"click .clickme": function(event,template) {
event.preventDefault();
// assign the correct item id to the reactive-var attached to this template instance
template.currentItemId.set(this._id);
}
});
HTML:
<template name="adminManageCategories">
{{#each category}}
<div class="clickme">{{title}}</div>
{{/each}}
<p>Current item title is : {{currentItem.title}}</p>
{{! pass the currentItem as a parameter to your child template this will be
accessible as {{item}} in the HTML and "this.item" in JS helpers or
"this.data.item" in created/rendered/destroyed callbacks}}
{{> adminUpdateCategory item=currentItem}}
</template>
编辑:
当我在created 回调中初始化reactive-var 时,我将它设置为null,这意味着在单击一项之前,帮助程序也将返回null,并且当您尝试访问this.item._id 时adminUpdateCategory 这将失败。
解决此问题的最简单方法可能是不将变量初始化为 null,而是将变量初始化为集合中的第一项。
Template.adminManageCategories.created=function(){
var firstItem=Items.findOne({},{
sort:{
sortedField:1
}
});
this.currentItemId=new ReactiveVar(firstItem && firstItem._id);
};
可能仍然存在集合中有 0 个项目的情况,因此您可能最终不得不防范 JS 中存在该项目。
Template.adminUpdateCategory.helpers({
itemProperty:function(){
return this.item && this.item.property;
}
});